PackageManagerService.java revision 528c3e572a829c51053532803ff31da123ebfed9
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.SET_HARMFUL_APP_WARNINGS;
21import static android.Manifest.permission.INSTALL_PACKAGES;
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.WRITE_EXTERNAL_STORAGE;
26import static android.Manifest.permission.WRITE_MEDIA_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.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
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.app.ActivityManager;
121import android.app.ActivityManagerInternal;
122import android.app.AppOpsManager;
123import android.app.IActivityManager;
124import android.app.ResourcesManager;
125import android.app.admin.IDevicePolicyManager;
126import android.app.admin.SecurityLog;
127import android.app.backup.IBackupManager;
128import android.content.BroadcastReceiver;
129import android.content.ComponentName;
130import android.content.ContentResolver;
131import android.content.Context;
132import android.content.IIntentReceiver;
133import android.content.Intent;
134import android.content.IntentFilter;
135import android.content.IntentSender;
136import android.content.IntentSender.SendIntentException;
137import android.content.ServiceConnection;
138import android.content.pm.ActivityInfo;
139import android.content.pm.ApplicationInfo;
140import android.content.pm.AppsQueryHelper;
141import android.content.pm.AuxiliaryResolveInfo;
142import android.content.pm.ChangedPackages;
143import android.content.pm.ComponentInfo;
144import android.content.pm.FallbackCategoryProvider;
145import android.content.pm.FeatureInfo;
146import android.content.pm.IDexModuleRegisterCallback;
147import android.content.pm.IOnPermissionsChangeListener;
148import android.content.pm.IPackageDataObserver;
149import android.content.pm.IPackageDeleteObserver;
150import android.content.pm.IPackageDeleteObserver2;
151import android.content.pm.IPackageInstallObserver2;
152import android.content.pm.IPackageInstaller;
153import android.content.pm.IPackageManager;
154import android.content.pm.IPackageManagerNative;
155import android.content.pm.IPackageMoveObserver;
156import android.content.pm.IPackageStatsObserver;
157import android.content.pm.InstantAppInfo;
158import android.content.pm.InstantAppRequest;
159import android.content.pm.InstantAppResolveInfo;
160import android.content.pm.InstrumentationInfo;
161import android.content.pm.IntentFilterVerificationInfo;
162import android.content.pm.KeySet;
163import android.content.pm.PackageCleanItem;
164import android.content.pm.PackageInfo;
165import android.content.pm.PackageInfoLite;
166import android.content.pm.PackageInstaller;
167import android.content.pm.PackageList;
168import android.content.pm.PackageManager;
169import android.content.pm.PackageManagerInternal;
170import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
171import android.content.pm.PackageManagerInternal.PackageListObserver;
172import android.content.pm.PackageParser;
173import android.content.pm.PackageParser.ActivityIntentInfo;
174import android.content.pm.PackageParser.Package;
175import android.content.pm.PackageParser.PackageLite;
176import android.content.pm.PackageParser.PackageParserException;
177import android.content.pm.PackageParser.ParseFlags;
178import android.content.pm.PackageParser.ServiceIntentInfo;
179import android.content.pm.PackageParser.SigningDetails;
180import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
181import android.content.pm.PackageStats;
182import android.content.pm.PackageUserState;
183import android.content.pm.ParceledListSlice;
184import android.content.pm.PermissionGroupInfo;
185import android.content.pm.PermissionInfo;
186import android.content.pm.ProviderInfo;
187import android.content.pm.ResolveInfo;
188import android.content.pm.ServiceInfo;
189import android.content.pm.SharedLibraryInfo;
190import android.content.pm.Signature;
191import android.content.pm.UserInfo;
192import android.content.pm.VerifierDeviceIdentity;
193import android.content.pm.VerifierInfo;
194import android.content.pm.VersionedPackage;
195import android.content.pm.dex.ArtManager;
196import android.content.pm.dex.DexMetadataHelper;
197import android.content.pm.dex.IArtManager;
198import android.content.res.Resources;
199import android.database.ContentObserver;
200import android.graphics.Bitmap;
201import android.hardware.display.DisplayManager;
202import android.net.Uri;
203import android.os.Binder;
204import android.os.Build;
205import android.os.Bundle;
206import android.os.Debug;
207import android.os.Environment;
208import android.os.Environment.UserEnvironment;
209import android.os.FileUtils;
210import android.os.Handler;
211import android.os.IBinder;
212import android.os.Looper;
213import android.os.Message;
214import android.os.Parcel;
215import android.os.ParcelFileDescriptor;
216import android.os.PatternMatcher;
217import android.os.Process;
218import android.os.RemoteCallbackList;
219import android.os.RemoteException;
220import android.os.ResultReceiver;
221import android.os.SELinux;
222import android.os.ServiceManager;
223import android.os.ShellCallback;
224import android.os.SystemClock;
225import android.os.SystemProperties;
226import android.os.Trace;
227import android.os.UserHandle;
228import android.os.UserManager;
229import android.os.UserManagerInternal;
230import android.os.storage.IStorageManager;
231import android.os.storage.StorageEventListener;
232import android.os.storage.StorageManager;
233import android.os.storage.StorageManagerInternal;
234import android.os.storage.VolumeInfo;
235import android.os.storage.VolumeRecord;
236import android.provider.Settings.Global;
237import android.provider.Settings.Secure;
238import android.security.KeyStore;
239import android.security.SystemKeyStore;
240import android.service.pm.PackageServiceDumpProto;
241import android.service.textclassifier.TextClassifierService;
242import android.system.ErrnoException;
243import android.system.Os;
244import android.text.TextUtils;
245import android.text.format.DateUtils;
246import android.util.ArrayMap;
247import android.util.ArraySet;
248import android.util.Base64;
249import android.util.ByteStringUtils;
250import android.util.DisplayMetrics;
251import android.util.EventLog;
252import android.util.ExceptionUtils;
253import android.util.Log;
254import android.util.LogPrinter;
255import android.util.LongSparseArray;
256import android.util.LongSparseLongArray;
257import android.util.MathUtils;
258import android.util.PackageUtils;
259import android.util.Pair;
260import android.util.PrintStreamPrinter;
261import android.util.Slog;
262import android.util.SparseArray;
263import android.util.SparseBooleanArray;
264import android.util.SparseIntArray;
265import android.util.TimingsTraceLog;
266import android.util.Xml;
267import android.util.jar.StrictJarFile;
268import android.util.proto.ProtoOutputStream;
269import android.view.Display;
270
271import com.android.internal.R;
272import com.android.internal.annotations.GuardedBy;
273import com.android.internal.app.IMediaContainerService;
274import com.android.internal.app.ResolverActivity;
275import com.android.internal.content.NativeLibraryHelper;
276import com.android.internal.content.PackageHelper;
277import com.android.internal.logging.MetricsLogger;
278import com.android.internal.os.IParcelFileDescriptorFactory;
279import com.android.internal.os.SomeArgs;
280import com.android.internal.os.Zygote;
281import com.android.internal.telephony.CarrierAppUtils;
282import com.android.internal.util.ArrayUtils;
283import com.android.internal.util.ConcurrentUtils;
284import com.android.internal.util.DumpUtils;
285import com.android.internal.util.FastXmlSerializer;
286import com.android.internal.util.IndentingPrintWriter;
287import com.android.internal.util.Preconditions;
288import com.android.internal.util.XmlUtils;
289import com.android.server.AttributeCache;
290import com.android.server.DeviceIdleController;
291import com.android.server.EventLogTags;
292import com.android.server.FgThread;
293import com.android.server.IntentResolver;
294import com.android.server.LocalServices;
295import com.android.server.LockGuard;
296import com.android.server.ServiceThread;
297import com.android.server.SystemConfig;
298import com.android.server.SystemServerInitThreadPool;
299import com.android.server.Watchdog;
300import com.android.server.net.NetworkPolicyManagerInternal;
301import com.android.server.pm.Installer.InstallerException;
302import com.android.server.pm.Settings.DatabaseVersion;
303import com.android.server.pm.Settings.VersionInfo;
304import com.android.server.pm.dex.ArtManagerService;
305import com.android.server.pm.dex.DexLogger;
306import com.android.server.pm.dex.DexManager;
307import com.android.server.pm.dex.DexoptOptions;
308import com.android.server.pm.dex.PackageDexUsage;
309import com.android.server.pm.permission.BasePermission;
310import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
311import com.android.server.pm.permission.PermissionManagerService;
312import com.android.server.pm.permission.PermissionManagerInternal;
313import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
314import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
315import com.android.server.pm.permission.PermissionsState;
316import com.android.server.pm.permission.PermissionsState.PermissionState;
317import com.android.server.security.VerityUtils;
318import com.android.server.storage.DeviceStorageMonitorInternal;
319
320import dalvik.system.CloseGuard;
321import dalvik.system.VMRuntime;
322
323import libcore.io.IoUtils;
324
325import org.xmlpull.v1.XmlPullParser;
326import org.xmlpull.v1.XmlPullParserException;
327import org.xmlpull.v1.XmlSerializer;
328
329import java.io.BufferedOutputStream;
330import java.io.ByteArrayInputStream;
331import java.io.ByteArrayOutputStream;
332import java.io.File;
333import java.io.FileDescriptor;
334import java.io.FileInputStream;
335import java.io.FileOutputStream;
336import java.io.FilenameFilter;
337import java.io.IOException;
338import java.io.PrintWriter;
339import java.lang.annotation.Retention;
340import java.lang.annotation.RetentionPolicy;
341import java.nio.charset.StandardCharsets;
342import java.security.DigestException;
343import java.security.DigestInputStream;
344import java.security.MessageDigest;
345import java.security.NoSuchAlgorithmException;
346import java.security.PublicKey;
347import java.security.SecureRandom;
348import java.security.cert.CertificateException;
349import java.util.ArrayList;
350import java.util.Arrays;
351import java.util.Collection;
352import java.util.Collections;
353import java.util.Comparator;
354import java.util.HashMap;
355import java.util.HashSet;
356import java.util.Iterator;
357import java.util.LinkedHashSet;
358import java.util.List;
359import java.util.Map;
360import java.util.Objects;
361import java.util.Set;
362import java.util.concurrent.CountDownLatch;
363import java.util.concurrent.Future;
364import java.util.concurrent.TimeUnit;
365import java.util.concurrent.atomic.AtomicBoolean;
366import java.util.concurrent.atomic.AtomicInteger;
367
368/**
369 * Keep track of all those APKs everywhere.
370 * <p>
371 * Internally there are two important locks:
372 * <ul>
373 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
374 * and other related state. It is a fine-grained lock that should only be held
375 * momentarily, as it's one of the most contended locks in the system.
376 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
377 * operations typically involve heavy lifting of application data on disk. Since
378 * {@code installd} is single-threaded, and it's operations can often be slow,
379 * this lock should never be acquired while already holding {@link #mPackages}.
380 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
381 * holding {@link #mInstallLock}.
382 * </ul>
383 * Many internal methods rely on the caller to hold the appropriate locks, and
384 * this contract is expressed through method name suffixes:
385 * <ul>
386 * <li>fooLI(): the caller must hold {@link #mInstallLock}
387 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
388 * being modified must be frozen
389 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
390 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
391 * </ul>
392 * <p>
393 * Because this class is very central to the platform's security; please run all
394 * CTS and unit tests whenever making modifications:
395 *
396 * <pre>
397 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
398 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
399 * </pre>
400 */
401public class PackageManagerService extends IPackageManager.Stub
402        implements PackageSender {
403    static final String TAG = "PackageManager";
404    public static final boolean DEBUG_SETTINGS = false;
405    static final boolean DEBUG_PREFERRED = false;
406    static final boolean DEBUG_UPGRADE = false;
407    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
408    private static final boolean DEBUG_BACKUP = false;
409    public static final boolean DEBUG_INSTALL = false;
410    public static final boolean DEBUG_REMOVE = false;
411    private static final boolean DEBUG_BROADCASTS = false;
412    private static final boolean DEBUG_SHOW_INFO = false;
413    private static final boolean DEBUG_PACKAGE_INFO = false;
414    private static final boolean DEBUG_INTENT_MATCHING = false;
415    public static final boolean DEBUG_PACKAGE_SCANNING = false;
416    private static final boolean DEBUG_VERIFY = false;
417    private static final boolean DEBUG_FILTERS = false;
418    public static final boolean DEBUG_PERMISSIONS = false;
419    private static final boolean DEBUG_SHARED_LIBRARIES = false;
420    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
421
422    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
423    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
424    // user, but by default initialize to this.
425    public static final boolean DEBUG_DEXOPT = false;
426
427    private static final boolean DEBUG_ABI_SELECTION = false;
428    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
429    private static final boolean DEBUG_TRIAGED_MISSING = false;
430    private static final boolean DEBUG_APP_DATA = false;
431
432    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
433    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
434
435    private static final boolean HIDE_EPHEMERAL_APIS = false;
436
437    private static final boolean ENABLE_FREE_CACHE_V2 =
438            SystemProperties.getBoolean("fw.free_cache_v2", true);
439
440    private static final int RADIO_UID = Process.PHONE_UID;
441    private static final int LOG_UID = Process.LOG_UID;
442    private static final int NFC_UID = Process.NFC_UID;
443    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
444    private static final int SHELL_UID = Process.SHELL_UID;
445    private static final int SE_UID = Process.SE_UID;
446
447    // Suffix used during package installation when copying/moving
448    // package apks to install directory.
449    private static final String INSTALL_PACKAGE_SUFFIX = "-";
450
451    static final int SCAN_NO_DEX = 1<<0;
452    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
453    static final int SCAN_NEW_INSTALL = 1<<2;
454    static final int SCAN_UPDATE_TIME = 1<<3;
455    static final int SCAN_BOOTING = 1<<4;
456    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
457    static final int SCAN_REQUIRE_KNOWN = 1<<7;
458    static final int SCAN_MOVE = 1<<8;
459    static final int SCAN_INITIAL = 1<<9;
460    static final int SCAN_CHECK_ONLY = 1<<10;
461    static final int SCAN_DONT_KILL_APP = 1<<11;
462    static final int SCAN_IGNORE_FROZEN = 1<<12;
463    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
464    static final int SCAN_AS_INSTANT_APP = 1<<14;
465    static final int SCAN_AS_FULL_APP = 1<<15;
466    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
467    static final int SCAN_AS_SYSTEM = 1<<17;
468    static final int SCAN_AS_PRIVILEGED = 1<<18;
469    static final int SCAN_AS_OEM = 1<<19;
470    static final int SCAN_AS_VENDOR = 1<<20;
471    static final int SCAN_AS_PRODUCT = 1<<21;
472
473    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
474            SCAN_NO_DEX,
475            SCAN_UPDATE_SIGNATURE,
476            SCAN_NEW_INSTALL,
477            SCAN_UPDATE_TIME,
478            SCAN_BOOTING,
479            SCAN_DELETE_DATA_ON_FAILURES,
480            SCAN_REQUIRE_KNOWN,
481            SCAN_MOVE,
482            SCAN_INITIAL,
483            SCAN_CHECK_ONLY,
484            SCAN_DONT_KILL_APP,
485            SCAN_IGNORE_FROZEN,
486            SCAN_FIRST_BOOT_OR_UPGRADE,
487            SCAN_AS_INSTANT_APP,
488            SCAN_AS_FULL_APP,
489            SCAN_AS_VIRTUAL_PRELOAD,
490    })
491    @Retention(RetentionPolicy.SOURCE)
492    public @interface ScanFlags {}
493
494    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
495    /** Extension of the compressed packages */
496    public final static String COMPRESSED_EXTENSION = ".gz";
497    /** Suffix of stub packages on the system partition */
498    public final static String STUB_SUFFIX = "-Stub";
499
500    private static final int[] EMPTY_INT_ARRAY = new int[0];
501
502    private static final int TYPE_UNKNOWN = 0;
503    private static final int TYPE_ACTIVITY = 1;
504    private static final int TYPE_RECEIVER = 2;
505    private static final int TYPE_SERVICE = 3;
506    private static final int TYPE_PROVIDER = 4;
507    @IntDef(prefix = { "TYPE_" }, value = {
508            TYPE_UNKNOWN,
509            TYPE_ACTIVITY,
510            TYPE_RECEIVER,
511            TYPE_SERVICE,
512            TYPE_PROVIDER,
513    })
514    @Retention(RetentionPolicy.SOURCE)
515    public @interface ComponentType {}
516
517    /**
518     * Timeout (in milliseconds) after which the watchdog should declare that
519     * our handler thread is wedged.  The usual default for such things is one
520     * minute but we sometimes do very lengthy I/O operations on this thread,
521     * such as installing multi-gigabyte applications, so ours needs to be longer.
522     */
523    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
524
525    /**
526     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
527     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
528     * settings entry if available, otherwise we use the hardcoded default.  If it's been
529     * more than this long since the last fstrim, we force one during the boot sequence.
530     *
531     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
532     * one gets run at the next available charging+idle time.  This final mandatory
533     * no-fstrim check kicks in only of the other scheduling criteria is never met.
534     */
535    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
536
537    /**
538     * Whether verification is enabled by default.
539     */
540    private static final boolean DEFAULT_VERIFY_ENABLE = true;
541
542    /**
543     * The default maximum time to wait for the verification agent to return in
544     * milliseconds.
545     */
546    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
547
548    /**
549     * The default response for package verification timeout.
550     *
551     * This can be either PackageManager.VERIFICATION_ALLOW or
552     * PackageManager.VERIFICATION_REJECT.
553     */
554    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
555
556    public static final String PLATFORM_PACKAGE_NAME = "android";
557
558    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
559
560    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
561            DEFAULT_CONTAINER_PACKAGE,
562            "com.android.defcontainer.DefaultContainerService");
563
564    private static final String KILL_APP_REASON_GIDS_CHANGED =
565            "permission grant or revoke changed gids";
566
567    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
568            "permissions revoked";
569
570    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
571
572    private static final String PACKAGE_SCHEME = "package";
573
574    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
575
576    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
577
578    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
579
580    /** Canonical intent used to identify what counts as a "web browser" app */
581    private static final Intent sBrowserIntent;
582    static {
583        sBrowserIntent = new Intent();
584        sBrowserIntent.setAction(Intent.ACTION_VIEW);
585        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
586        sBrowserIntent.setData(Uri.parse("http:"));
587        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
588    }
589
590    /**
591     * The set of all protected actions [i.e. those actions for which a high priority
592     * intent filter is disallowed].
593     */
594    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
595    static {
596        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
597        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
598        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
599        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
600    }
601
602    // Compilation reasons.
603    public static final int REASON_UNKNOWN = -1;
604    public static final int REASON_FIRST_BOOT = 0;
605    public static final int REASON_BOOT = 1;
606    public static final int REASON_INSTALL = 2;
607    public static final int REASON_BACKGROUND_DEXOPT = 3;
608    public static final int REASON_AB_OTA = 4;
609    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
610    public static final int REASON_SHARED = 6;
611
612    public static final int REASON_LAST = REASON_SHARED;
613
614    /**
615     * Version number for the package parser cache. Increment this whenever the format or
616     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
617     */
618    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
619
620    /**
621     * Whether the package parser cache is enabled.
622     */
623    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
624
625    /**
626     * Permissions required in order to receive instant application lifecycle broadcasts.
627     */
628    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
629            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
630
631    final ServiceThread mHandlerThread;
632
633    final PackageHandler mHandler;
634
635    private final ProcessLoggingHandler mProcessLoggingHandler;
636
637    /**
638     * Messages for {@link #mHandler} that need to wait for system ready before
639     * being dispatched.
640     */
641    private ArrayList<Message> mPostSystemReadyMessages;
642
643    final int mSdkVersion = Build.VERSION.SDK_INT;
644
645    final Context mContext;
646    final boolean mFactoryTest;
647    final boolean mOnlyCore;
648    final DisplayMetrics mMetrics;
649    final int mDefParseFlags;
650    final String[] mSeparateProcesses;
651    final boolean mIsUpgrade;
652    final boolean mIsPreNUpgrade;
653    final boolean mIsPreNMR1Upgrade;
654
655    // Have we told the Activity Manager to whitelist the default container service by uid yet?
656    @GuardedBy("mPackages")
657    boolean mDefaultContainerWhitelisted = false;
658
659    @GuardedBy("mPackages")
660    private boolean mDexOptDialogShown;
661
662    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
663    // LOCK HELD.  Can be called with mInstallLock held.
664    @GuardedBy("mInstallLock")
665    final Installer mInstaller;
666
667    /** Directory where installed applications are stored */
668    private static final File sAppInstallDir =
669            new File(Environment.getDataDirectory(), "app");
670    /** Directory where installed application's 32-bit native libraries are copied. */
671    private static final File sAppLib32InstallDir =
672            new File(Environment.getDataDirectory(), "app-lib");
673    /** Directory where code and non-resource assets of forward-locked applications are stored */
674    private static final File sDrmAppPrivateInstallDir =
675            new File(Environment.getDataDirectory(), "app-private");
676
677    // ----------------------------------------------------------------
678
679    // Lock for state used when installing and doing other long running
680    // operations.  Methods that must be called with this lock held have
681    // the suffix "LI".
682    final Object mInstallLock = new Object();
683
684    // ----------------------------------------------------------------
685
686    // Keys are String (package name), values are Package.  This also serves
687    // as the lock for the global state.  Methods that must be called with
688    // this lock held have the prefix "LP".
689    @GuardedBy("mPackages")
690    final ArrayMap<String, PackageParser.Package> mPackages =
691            new ArrayMap<String, PackageParser.Package>();
692
693    final ArrayMap<String, Set<String>> mKnownCodebase =
694            new ArrayMap<String, Set<String>>();
695
696    // Keys are isolated uids and values are the uid of the application
697    // that created the isolated proccess.
698    @GuardedBy("mPackages")
699    final SparseIntArray mIsolatedOwners = new SparseIntArray();
700
701    /**
702     * Tracks new system packages [received in an OTA] that we expect to
703     * find updated user-installed versions. Keys are package name, values
704     * are package location.
705     */
706    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
707    /**
708     * Tracks high priority intent filters for protected actions. During boot, certain
709     * filter actions are protected and should never be allowed to have a high priority
710     * intent filter for them. However, there is one, and only one exception -- the
711     * setup wizard. It must be able to define a high priority intent filter for these
712     * actions to ensure there are no escapes from the wizard. We need to delay processing
713     * of these during boot as we need to look at all of the system packages in order
714     * to know which component is the setup wizard.
715     */
716    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
717    /**
718     * Whether or not processing protected filters should be deferred.
719     */
720    private boolean mDeferProtectedFilters = true;
721
722    /**
723     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
724     */
725    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
726    /**
727     * Whether or not system app permissions should be promoted from install to runtime.
728     */
729    boolean mPromoteSystemApps;
730
731    @GuardedBy("mPackages")
732    final Settings mSettings;
733
734    /**
735     * Set of package names that are currently "frozen", which means active
736     * surgery is being done on the code/data for that package. The platform
737     * will refuse to launch frozen packages to avoid race conditions.
738     *
739     * @see PackageFreezer
740     */
741    @GuardedBy("mPackages")
742    final ArraySet<String> mFrozenPackages = new ArraySet<>();
743
744    final ProtectedPackages mProtectedPackages;
745
746    @GuardedBy("mLoadedVolumes")
747    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
748
749    boolean mFirstBoot;
750
751    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
752
753    @GuardedBy("mAvailableFeatures")
754    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
755
756    private final InstantAppRegistry mInstantAppRegistry;
757
758    @GuardedBy("mPackages")
759    int mChangedPackagesSequenceNumber;
760    /**
761     * List of changed [installed, removed or updated] packages.
762     * mapping from user id -> sequence number -> package name
763     */
764    @GuardedBy("mPackages")
765    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
766    /**
767     * The sequence number of the last change to a package.
768     * mapping from user id -> package name -> sequence number
769     */
770    @GuardedBy("mPackages")
771    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
772
773    @GuardedBy("mPackages")
774    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
775
776    class PackageParserCallback implements PackageParser.Callback {
777        @Override public final boolean hasFeature(String feature) {
778            return PackageManagerService.this.hasSystemFeature(feature, 0);
779        }
780
781        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
782                Collection<PackageParser.Package> allPackages, String targetPackageName) {
783            List<PackageParser.Package> overlayPackages = null;
784            for (PackageParser.Package p : allPackages) {
785                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
786                    if (overlayPackages == null) {
787                        overlayPackages = new ArrayList<PackageParser.Package>();
788                    }
789                    overlayPackages.add(p);
790                }
791            }
792            if (overlayPackages != null) {
793                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
794                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
795                        return p1.mOverlayPriority - p2.mOverlayPriority;
796                    }
797                };
798                Collections.sort(overlayPackages, cmp);
799            }
800            return overlayPackages;
801        }
802
803        @GuardedBy("mInstallLock")
804        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
805                String targetPackageName, String targetPath) {
806            if ("android".equals(targetPackageName)) {
807                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
808                // native AssetManager.
809                return null;
810            }
811            List<PackageParser.Package> overlayPackages =
812                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
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            synchronized (mPackages) {
849                return getStaticOverlayPathsLocked(
850                        mPackages.values(), targetPackageName, targetPath);
851            }
852        }
853
854        @Override public final String[] getOverlayApks(String targetPackageName) {
855            return getStaticOverlayPaths(targetPackageName, null);
856        }
857
858        @Override public final String[] getOverlayPaths(String targetPackageName,
859                String targetPath) {
860            return getStaticOverlayPaths(targetPackageName, targetPath);
861        }
862    }
863
864    class ParallelPackageParserCallback extends PackageParserCallback {
865        List<PackageParser.Package> mOverlayPackages = null;
866
867        void findStaticOverlayPackages() {
868            synchronized (mPackages) {
869                for (PackageParser.Package p : mPackages.values()) {
870                    if (p.mOverlayIsStatic) {
871                        if (mOverlayPackages == null) {
872                            mOverlayPackages = new ArrayList<PackageParser.Package>();
873                        }
874                        mOverlayPackages.add(p);
875                    }
876                }
877            }
878        }
879
880        @Override
881        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
882            // We can trust mOverlayPackages without holding mPackages because package uninstall
883            // can't happen while running parallel parsing.
884            // Moreover holding mPackages on each parsing thread causes dead-lock.
885            return mOverlayPackages == null ? null :
886                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
887        }
888    }
889
890    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
891    final ParallelPackageParserCallback mParallelPackageParserCallback =
892            new ParallelPackageParserCallback();
893
894    public static final class SharedLibraryEntry {
895        public final @Nullable String path;
896        public final @Nullable String apk;
897        public final @NonNull SharedLibraryInfo info;
898
899        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
900                String declaringPackageName, long declaringPackageVersionCode) {
901            path = _path;
902            apk = _apk;
903            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
904                    declaringPackageName, declaringPackageVersionCode), null);
905        }
906    }
907
908    // Currently known shared libraries.
909    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
910    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
911            new ArrayMap<>();
912
913    // All available activities, for your resolving pleasure.
914    final ActivityIntentResolver mActivities =
915            new ActivityIntentResolver();
916
917    // All available receivers, for your resolving pleasure.
918    final ActivityIntentResolver mReceivers =
919            new ActivityIntentResolver();
920
921    // All available services, for your resolving pleasure.
922    final ServiceIntentResolver mServices = new ServiceIntentResolver();
923
924    // All available providers, for your resolving pleasure.
925    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
926
927    // Mapping from provider base names (first directory in content URI codePath)
928    // to the provider information.
929    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
930            new ArrayMap<String, PackageParser.Provider>();
931
932    // Mapping from instrumentation class names to info about them.
933    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
934            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
935
936    // Packages whose data we have transfered into another package, thus
937    // should no longer exist.
938    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
939
940    // Broadcast actions that are only available to the system.
941    @GuardedBy("mProtectedBroadcasts")
942    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
943
944    /** List of packages waiting for verification. */
945    final SparseArray<PackageVerificationState> mPendingVerification
946            = new SparseArray<PackageVerificationState>();
947
948    final PackageInstallerService mInstallerService;
949
950    final ArtManagerService mArtManagerService;
951
952    private final PackageDexOptimizer mPackageDexOptimizer;
953    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
954    // is used by other apps).
955    private final DexManager mDexManager;
956
957    private AtomicInteger mNextMoveId = new AtomicInteger();
958    private final MoveCallbacks mMoveCallbacks;
959
960    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
961
962    // Cache of users who need badging.
963    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
964
965    /** Token for keys in mPendingVerification. */
966    private int mPendingVerificationToken = 0;
967
968    volatile boolean mSystemReady;
969    volatile boolean mSafeMode;
970    volatile boolean mHasSystemUidErrors;
971    private volatile boolean mWebInstantAppsDisabled;
972
973    ApplicationInfo mAndroidApplication;
974    final ActivityInfo mResolveActivity = new ActivityInfo();
975    final ResolveInfo mResolveInfo = new ResolveInfo();
976    ComponentName mResolveComponentName;
977    PackageParser.Package mPlatformPackage;
978    ComponentName mCustomResolverComponentName;
979
980    boolean mResolverReplaced = false;
981
982    private final @Nullable ComponentName mIntentFilterVerifierComponent;
983    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
984
985    private int mIntentFilterVerificationToken = 0;
986
987    /** The service connection to the ephemeral resolver */
988    final InstantAppResolverConnection mInstantAppResolverConnection;
989    /** Component used to show resolver settings for Instant Apps */
990    final ComponentName mInstantAppResolverSettingsComponent;
991
992    /** Activity used to install instant applications */
993    ActivityInfo mInstantAppInstallerActivity;
994    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
995
996    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
997            = new SparseArray<IntentFilterVerificationState>();
998
999    // TODO remove this and go through mPermissonManager directly
1000    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1001    private final PermissionManagerInternal mPermissionManager;
1002
1003    // List of packages names to keep cached, even if they are uninstalled for all users
1004    private List<String> mKeepUninstalledPackages;
1005
1006    private UserManagerInternal mUserManagerInternal;
1007    private ActivityManagerInternal mActivityManagerInternal;
1008
1009    private DeviceIdleController.LocalService mDeviceIdleController;
1010
1011    private File mCacheDir;
1012
1013    private Future<?> mPrepareAppDataFuture;
1014
1015    private static class IFVerificationParams {
1016        PackageParser.Package pkg;
1017        boolean replacing;
1018        int userId;
1019        int verifierUid;
1020
1021        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1022                int _userId, int _verifierUid) {
1023            pkg = _pkg;
1024            replacing = _replacing;
1025            userId = _userId;
1026            replacing = _replacing;
1027            verifierUid = _verifierUid;
1028        }
1029    }
1030
1031    private interface IntentFilterVerifier<T extends IntentFilter> {
1032        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1033                                               T filter, String packageName);
1034        void startVerifications(int userId);
1035        void receiveVerificationResponse(int verificationId);
1036    }
1037
1038    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1039        private Context mContext;
1040        private ComponentName mIntentFilterVerifierComponent;
1041        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1042
1043        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1044            mContext = context;
1045            mIntentFilterVerifierComponent = verifierComponent;
1046        }
1047
1048        private String getDefaultScheme() {
1049            return IntentFilter.SCHEME_HTTPS;
1050        }
1051
1052        @Override
1053        public void startVerifications(int userId) {
1054            // Launch verifications requests
1055            int count = mCurrentIntentFilterVerifications.size();
1056            for (int n=0; n<count; n++) {
1057                int verificationId = mCurrentIntentFilterVerifications.get(n);
1058                final IntentFilterVerificationState ivs =
1059                        mIntentFilterVerificationStates.get(verificationId);
1060
1061                String packageName = ivs.getPackageName();
1062
1063                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1064                final int filterCount = filters.size();
1065                ArraySet<String> domainsSet = new ArraySet<>();
1066                for (int m=0; m<filterCount; m++) {
1067                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1068                    domainsSet.addAll(filter.getHostsList());
1069                }
1070                synchronized (mPackages) {
1071                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1072                            packageName, domainsSet) != null) {
1073                        scheduleWriteSettingsLocked();
1074                    }
1075                }
1076                sendVerificationRequest(verificationId, ivs);
1077            }
1078            mCurrentIntentFilterVerifications.clear();
1079        }
1080
1081        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1082            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1083            verificationIntent.putExtra(
1084                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1085                    verificationId);
1086            verificationIntent.putExtra(
1087                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1088                    getDefaultScheme());
1089            verificationIntent.putExtra(
1090                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1091                    ivs.getHostsString());
1092            verificationIntent.putExtra(
1093                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1094                    ivs.getPackageName());
1095            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1096            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1097
1098            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1099            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1100                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1101                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1102
1103            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1104            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1105                    "Sending IntentFilter verification broadcast");
1106        }
1107
1108        public void receiveVerificationResponse(int verificationId) {
1109            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1110
1111            final boolean verified = ivs.isVerified();
1112
1113            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1114            final int count = filters.size();
1115            if (DEBUG_DOMAIN_VERIFICATION) {
1116                Slog.i(TAG, "Received verification response " + verificationId
1117                        + " for " + count + " filters, verified=" + verified);
1118            }
1119            for (int n=0; n<count; n++) {
1120                PackageParser.ActivityIntentInfo filter = filters.get(n);
1121                filter.setVerified(verified);
1122
1123                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1124                        + " verified with result:" + verified + " and hosts:"
1125                        + ivs.getHostsString());
1126            }
1127
1128            mIntentFilterVerificationStates.remove(verificationId);
1129
1130            final String packageName = ivs.getPackageName();
1131            IntentFilterVerificationInfo ivi = null;
1132
1133            synchronized (mPackages) {
1134                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1135            }
1136            if (ivi == null) {
1137                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1138                        + verificationId + " packageName:" + packageName);
1139                return;
1140            }
1141            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1142                    "Updating IntentFilterVerificationInfo for package " + packageName
1143                            +" verificationId:" + verificationId);
1144
1145            synchronized (mPackages) {
1146                if (verified) {
1147                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1148                } else {
1149                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1150                }
1151                scheduleWriteSettingsLocked();
1152
1153                final int userId = ivs.getUserId();
1154                if (userId != UserHandle.USER_ALL) {
1155                    final int userStatus =
1156                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1157
1158                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1159                    boolean needUpdate = false;
1160
1161                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1162                    // already been set by the User thru the Disambiguation dialog
1163                    switch (userStatus) {
1164                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1165                            if (verified) {
1166                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1167                            } else {
1168                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1169                            }
1170                            needUpdate = true;
1171                            break;
1172
1173                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1174                            if (verified) {
1175                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1176                                needUpdate = true;
1177                            }
1178                            break;
1179
1180                        default:
1181                            // Nothing to do
1182                    }
1183
1184                    if (needUpdate) {
1185                        mSettings.updateIntentFilterVerificationStatusLPw(
1186                                packageName, updatedStatus, userId);
1187                        scheduleWritePackageRestrictionsLocked(userId);
1188                    }
1189                }
1190            }
1191        }
1192
1193        @Override
1194        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1195                    ActivityIntentInfo filter, String packageName) {
1196            if (!hasValidDomains(filter)) {
1197                return false;
1198            }
1199            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1200            if (ivs == null) {
1201                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1202                        packageName);
1203            }
1204            if (DEBUG_DOMAIN_VERIFICATION) {
1205                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1206            }
1207            ivs.addFilter(filter);
1208            return true;
1209        }
1210
1211        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1212                int userId, int verificationId, String packageName) {
1213            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1214                    verifierUid, userId, packageName);
1215            ivs.setPendingState();
1216            synchronized (mPackages) {
1217                mIntentFilterVerificationStates.append(verificationId, ivs);
1218                mCurrentIntentFilterVerifications.add(verificationId);
1219            }
1220            return ivs;
1221        }
1222    }
1223
1224    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1225        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1226                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1227                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1228    }
1229
1230    // Set of pending broadcasts for aggregating enable/disable of components.
1231    static class PendingPackageBroadcasts {
1232        // for each user id, a map of <package name -> components within that package>
1233        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1234
1235        public PendingPackageBroadcasts() {
1236            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1237        }
1238
1239        public ArrayList<String> get(int userId, String packageName) {
1240            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1241            return packages.get(packageName);
1242        }
1243
1244        public void put(int userId, String packageName, ArrayList<String> components) {
1245            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1246            packages.put(packageName, components);
1247        }
1248
1249        public void remove(int userId, String packageName) {
1250            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1251            if (packages != null) {
1252                packages.remove(packageName);
1253            }
1254        }
1255
1256        public void remove(int userId) {
1257            mUidMap.remove(userId);
1258        }
1259
1260        public int userIdCount() {
1261            return mUidMap.size();
1262        }
1263
1264        public int userIdAt(int n) {
1265            return mUidMap.keyAt(n);
1266        }
1267
1268        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1269            return mUidMap.get(userId);
1270        }
1271
1272        public int size() {
1273            // total number of pending broadcast entries across all userIds
1274            int num = 0;
1275            for (int i = 0; i< mUidMap.size(); i++) {
1276                num += mUidMap.valueAt(i).size();
1277            }
1278            return num;
1279        }
1280
1281        public void clear() {
1282            mUidMap.clear();
1283        }
1284
1285        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1286            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1287            if (map == null) {
1288                map = new ArrayMap<String, ArrayList<String>>();
1289                mUidMap.put(userId, map);
1290            }
1291            return map;
1292        }
1293    }
1294    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1295
1296    // Service Connection to remote media container service to copy
1297    // package uri's from external media onto secure containers
1298    // or internal storage.
1299    private IMediaContainerService mContainerService = null;
1300
1301    static final int SEND_PENDING_BROADCAST = 1;
1302    static final int MCS_BOUND = 3;
1303    static final int END_COPY = 4;
1304    static final int INIT_COPY = 5;
1305    static final int MCS_UNBIND = 6;
1306    static final int START_CLEANING_PACKAGE = 7;
1307    static final int FIND_INSTALL_LOC = 8;
1308    static final int POST_INSTALL = 9;
1309    static final int MCS_RECONNECT = 10;
1310    static final int MCS_GIVE_UP = 11;
1311    static final int WRITE_SETTINGS = 13;
1312    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1313    static final int PACKAGE_VERIFIED = 15;
1314    static final int CHECK_PENDING_VERIFICATION = 16;
1315    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1316    static final int INTENT_FILTER_VERIFIED = 18;
1317    static final int WRITE_PACKAGE_LIST = 19;
1318    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1319
1320    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1321
1322    // Delay time in millisecs
1323    static final int BROADCAST_DELAY = 10 * 1000;
1324
1325    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1326            2 * 60 * 60 * 1000L; /* two hours */
1327
1328    static UserManagerService sUserManager;
1329
1330    // Stores a list of users whose package restrictions file needs to be updated
1331    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1332
1333    final private DefaultContainerConnection mDefContainerConn =
1334            new DefaultContainerConnection();
1335    class DefaultContainerConnection implements ServiceConnection {
1336        public void onServiceConnected(ComponentName name, IBinder service) {
1337            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1338            final IMediaContainerService imcs = IMediaContainerService.Stub
1339                    .asInterface(Binder.allowBlocking(service));
1340            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1341        }
1342
1343        public void onServiceDisconnected(ComponentName name) {
1344            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1345        }
1346    }
1347
1348    // Recordkeeping of restore-after-install operations that are currently in flight
1349    // between the Package Manager and the Backup Manager
1350    static class PostInstallData {
1351        public InstallArgs args;
1352        public PackageInstalledInfo res;
1353
1354        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1355            args = _a;
1356            res = _r;
1357        }
1358    }
1359
1360    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1361    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1362
1363    // XML tags for backup/restore of various bits of state
1364    private static final String TAG_PREFERRED_BACKUP = "pa";
1365    private static final String TAG_DEFAULT_APPS = "da";
1366    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1367
1368    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1369    private static final String TAG_ALL_GRANTS = "rt-grants";
1370    private static final String TAG_GRANT = "grant";
1371    private static final String ATTR_PACKAGE_NAME = "pkg";
1372
1373    private static final String TAG_PERMISSION = "perm";
1374    private static final String ATTR_PERMISSION_NAME = "name";
1375    private static final String ATTR_IS_GRANTED = "g";
1376    private static final String ATTR_USER_SET = "set";
1377    private static final String ATTR_USER_FIXED = "fixed";
1378    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1379
1380    // System/policy permission grants are not backed up
1381    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1382            FLAG_PERMISSION_POLICY_FIXED
1383            | FLAG_PERMISSION_SYSTEM_FIXED
1384            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1385
1386    // And we back up these user-adjusted states
1387    private static final int USER_RUNTIME_GRANT_MASK =
1388            FLAG_PERMISSION_USER_SET
1389            | FLAG_PERMISSION_USER_FIXED
1390            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1391
1392    final @Nullable String mRequiredVerifierPackage;
1393    final @NonNull String mRequiredInstallerPackage;
1394    final @NonNull String mRequiredUninstallerPackage;
1395    final @Nullable String mSetupWizardPackage;
1396    final @Nullable String mStorageManagerPackage;
1397    final @Nullable String mSystemTextClassifierPackage;
1398    final @NonNull String mServicesSystemSharedLibraryPackageName;
1399    final @NonNull String mSharedSystemSharedLibraryPackageName;
1400
1401    private final PackageUsage mPackageUsage = new PackageUsage();
1402    private final CompilerStats mCompilerStats = new CompilerStats();
1403
1404    class PackageHandler extends Handler {
1405        private boolean mBound = false;
1406        final ArrayList<HandlerParams> mPendingInstalls =
1407            new ArrayList<HandlerParams>();
1408
1409        private boolean connectToService() {
1410            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1411                    " DefaultContainerService");
1412            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1413            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1414            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1415                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1416                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1417                mBound = true;
1418                return true;
1419            }
1420            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1421            return false;
1422        }
1423
1424        private void disconnectService() {
1425            mContainerService = null;
1426            mBound = false;
1427            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1428            mContext.unbindService(mDefContainerConn);
1429            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1430        }
1431
1432        PackageHandler(Looper looper) {
1433            super(looper);
1434        }
1435
1436        public void handleMessage(Message msg) {
1437            try {
1438                doHandleMessage(msg);
1439            } finally {
1440                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1441            }
1442        }
1443
1444        void doHandleMessage(Message msg) {
1445            switch (msg.what) {
1446                case INIT_COPY: {
1447                    HandlerParams params = (HandlerParams) msg.obj;
1448                    int idx = mPendingInstalls.size();
1449                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1450                    // If a bind was already initiated we dont really
1451                    // need to do anything. The pending install
1452                    // will be processed later on.
1453                    if (!mBound) {
1454                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1455                                System.identityHashCode(mHandler));
1456                        // If this is the only one pending we might
1457                        // have to bind to the service again.
1458                        if (!connectToService()) {
1459                            Slog.e(TAG, "Failed to bind to media container service");
1460                            params.serviceError();
1461                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1462                                    System.identityHashCode(mHandler));
1463                            if (params.traceMethod != null) {
1464                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1465                                        params.traceCookie);
1466                            }
1467                            return;
1468                        } else {
1469                            // Once we bind to the service, the first
1470                            // pending request will be processed.
1471                            mPendingInstalls.add(idx, params);
1472                        }
1473                    } else {
1474                        mPendingInstalls.add(idx, params);
1475                        // Already bound to the service. Just make
1476                        // sure we trigger off processing the first request.
1477                        if (idx == 0) {
1478                            mHandler.sendEmptyMessage(MCS_BOUND);
1479                        }
1480                    }
1481                    break;
1482                }
1483                case MCS_BOUND: {
1484                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1485                    if (msg.obj != null) {
1486                        mContainerService = (IMediaContainerService) msg.obj;
1487                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1488                                System.identityHashCode(mHandler));
1489                    }
1490                    if (mContainerService == null) {
1491                        if (!mBound) {
1492                            // Something seriously wrong since we are not bound and we are not
1493                            // waiting for connection. Bail out.
1494                            Slog.e(TAG, "Cannot bind to media container service");
1495                            for (HandlerParams params : mPendingInstalls) {
1496                                // Indicate service bind error
1497                                params.serviceError();
1498                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1499                                        System.identityHashCode(params));
1500                                if (params.traceMethod != null) {
1501                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1502                                            params.traceMethod, params.traceCookie);
1503                                }
1504                                return;
1505                            }
1506                            mPendingInstalls.clear();
1507                        } else {
1508                            Slog.w(TAG, "Waiting to connect to media container service");
1509                        }
1510                    } else if (mPendingInstalls.size() > 0) {
1511                        HandlerParams params = mPendingInstalls.get(0);
1512                        if (params != null) {
1513                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1514                                    System.identityHashCode(params));
1515                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1516                            if (params.startCopy()) {
1517                                // We are done...  look for more work or to
1518                                // go idle.
1519                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1520                                        "Checking for more work or unbind...");
1521                                // Delete pending install
1522                                if (mPendingInstalls.size() > 0) {
1523                                    mPendingInstalls.remove(0);
1524                                }
1525                                if (mPendingInstalls.size() == 0) {
1526                                    if (mBound) {
1527                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1528                                                "Posting delayed MCS_UNBIND");
1529                                        removeMessages(MCS_UNBIND);
1530                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1531                                        // Unbind after a little delay, to avoid
1532                                        // continual thrashing.
1533                                        sendMessageDelayed(ubmsg, 10000);
1534                                    }
1535                                } else {
1536                                    // There are more pending requests in queue.
1537                                    // Just post MCS_BOUND message to trigger processing
1538                                    // of next pending install.
1539                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1540                                            "Posting MCS_BOUND for next work");
1541                                    mHandler.sendEmptyMessage(MCS_BOUND);
1542                                }
1543                            }
1544                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1545                        }
1546                    } else {
1547                        // Should never happen ideally.
1548                        Slog.w(TAG, "Empty queue");
1549                    }
1550                    break;
1551                }
1552                case MCS_RECONNECT: {
1553                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1554                    if (mPendingInstalls.size() > 0) {
1555                        if (mBound) {
1556                            disconnectService();
1557                        }
1558                        if (!connectToService()) {
1559                            Slog.e(TAG, "Failed to bind to media container service");
1560                            for (HandlerParams params : mPendingInstalls) {
1561                                // Indicate service bind error
1562                                params.serviceError();
1563                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1564                                        System.identityHashCode(params));
1565                            }
1566                            mPendingInstalls.clear();
1567                        }
1568                    }
1569                    break;
1570                }
1571                case MCS_UNBIND: {
1572                    // If there is no actual work left, then time to unbind.
1573                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1574
1575                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1576                        if (mBound) {
1577                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1578
1579                            disconnectService();
1580                        }
1581                    } else if (mPendingInstalls.size() > 0) {
1582                        // There are more pending requests in queue.
1583                        // Just post MCS_BOUND message to trigger processing
1584                        // of next pending install.
1585                        mHandler.sendEmptyMessage(MCS_BOUND);
1586                    }
1587
1588                    break;
1589                }
1590                case MCS_GIVE_UP: {
1591                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1592                    HandlerParams params = mPendingInstalls.remove(0);
1593                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1594                            System.identityHashCode(params));
1595                    break;
1596                }
1597                case SEND_PENDING_BROADCAST: {
1598                    String packages[];
1599                    ArrayList<String> components[];
1600                    int size = 0;
1601                    int uids[];
1602                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1603                    synchronized (mPackages) {
1604                        if (mPendingBroadcasts == null) {
1605                            return;
1606                        }
1607                        size = mPendingBroadcasts.size();
1608                        if (size <= 0) {
1609                            // Nothing to be done. Just return
1610                            return;
1611                        }
1612                        packages = new String[size];
1613                        components = new ArrayList[size];
1614                        uids = new int[size];
1615                        int i = 0;  // filling out the above arrays
1616
1617                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1618                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1619                            Iterator<Map.Entry<String, ArrayList<String>>> it
1620                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1621                                            .entrySet().iterator();
1622                            while (it.hasNext() && i < size) {
1623                                Map.Entry<String, ArrayList<String>> ent = it.next();
1624                                packages[i] = ent.getKey();
1625                                components[i] = ent.getValue();
1626                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1627                                uids[i] = (ps != null)
1628                                        ? UserHandle.getUid(packageUserId, ps.appId)
1629                                        : -1;
1630                                i++;
1631                            }
1632                        }
1633                        size = i;
1634                        mPendingBroadcasts.clear();
1635                    }
1636                    // Send broadcasts
1637                    for (int i = 0; i < size; i++) {
1638                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1639                    }
1640                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1641                    break;
1642                }
1643                case START_CLEANING_PACKAGE: {
1644                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1645                    final String packageName = (String)msg.obj;
1646                    final int userId = msg.arg1;
1647                    final boolean andCode = msg.arg2 != 0;
1648                    synchronized (mPackages) {
1649                        if (userId == UserHandle.USER_ALL) {
1650                            int[] users = sUserManager.getUserIds();
1651                            for (int user : users) {
1652                                mSettings.addPackageToCleanLPw(
1653                                        new PackageCleanItem(user, packageName, andCode));
1654                            }
1655                        } else {
1656                            mSettings.addPackageToCleanLPw(
1657                                    new PackageCleanItem(userId, packageName, andCode));
1658                        }
1659                    }
1660                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1661                    startCleaningPackages();
1662                } break;
1663                case POST_INSTALL: {
1664                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1665
1666                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1667                    final boolean didRestore = (msg.arg2 != 0);
1668                    mRunningInstalls.delete(msg.arg1);
1669
1670                    if (data != null) {
1671                        InstallArgs args = data.args;
1672                        PackageInstalledInfo parentRes = data.res;
1673
1674                        final boolean grantPermissions = (args.installFlags
1675                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1676                        final boolean killApp = (args.installFlags
1677                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1678                        final boolean virtualPreload = ((args.installFlags
1679                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1680                        final String[] grantedPermissions = args.installGrantPermissions;
1681
1682                        // Handle the parent package
1683                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1684                                virtualPreload, grantedPermissions, didRestore,
1685                                args.installerPackageName, args.observer);
1686
1687                        // Handle the child packages
1688                        final int childCount = (parentRes.addedChildPackages != null)
1689                                ? parentRes.addedChildPackages.size() : 0;
1690                        for (int i = 0; i < childCount; i++) {
1691                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1692                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1693                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1694                                    args.installerPackageName, args.observer);
1695                        }
1696
1697                        // Log tracing if needed
1698                        if (args.traceMethod != null) {
1699                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1700                                    args.traceCookie);
1701                        }
1702                    } else {
1703                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1704                    }
1705
1706                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1707                } break;
1708                case WRITE_SETTINGS: {
1709                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1710                    synchronized (mPackages) {
1711                        removeMessages(WRITE_SETTINGS);
1712                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1713                        mSettings.writeLPr();
1714                        mDirtyUsers.clear();
1715                    }
1716                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1717                } break;
1718                case WRITE_PACKAGE_RESTRICTIONS: {
1719                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1720                    synchronized (mPackages) {
1721                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1722                        for (int userId : mDirtyUsers) {
1723                            mSettings.writePackageRestrictionsLPr(userId);
1724                        }
1725                        mDirtyUsers.clear();
1726                    }
1727                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1728                } break;
1729                case WRITE_PACKAGE_LIST: {
1730                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1731                    synchronized (mPackages) {
1732                        removeMessages(WRITE_PACKAGE_LIST);
1733                        mSettings.writePackageListLPr(msg.arg1);
1734                    }
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1736                } break;
1737                case CHECK_PENDING_VERIFICATION: {
1738                    final int verificationId = msg.arg1;
1739                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1740
1741                    if ((state != null) && !state.timeoutExtended()) {
1742                        final InstallArgs args = state.getInstallArgs();
1743                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1744
1745                        Slog.i(TAG, "Verification timed out for " + originUri);
1746                        mPendingVerification.remove(verificationId);
1747
1748                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1749
1750                        final UserHandle user = args.getUser();
1751                        if (getDefaultVerificationResponse(user)
1752                                == PackageManager.VERIFICATION_ALLOW) {
1753                            Slog.i(TAG, "Continuing with installation of " + originUri);
1754                            state.setVerifierResponse(Binder.getCallingUid(),
1755                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1756                            broadcastPackageVerified(verificationId, originUri,
1757                                    PackageManager.VERIFICATION_ALLOW, user);
1758                            try {
1759                                ret = args.copyApk(mContainerService, true);
1760                            } catch (RemoteException e) {
1761                                Slog.e(TAG, "Could not contact the ContainerService");
1762                            }
1763                        } else {
1764                            broadcastPackageVerified(verificationId, originUri,
1765                                    PackageManager.VERIFICATION_REJECT, user);
1766                        }
1767
1768                        Trace.asyncTraceEnd(
1769                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1770
1771                        processPendingInstall(args, ret);
1772                        mHandler.sendEmptyMessage(MCS_UNBIND);
1773                    }
1774                    break;
1775                }
1776                case PACKAGE_VERIFIED: {
1777                    final int verificationId = msg.arg1;
1778
1779                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1780                    if (state == null) {
1781                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1782                        break;
1783                    }
1784
1785                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1786
1787                    state.setVerifierResponse(response.callerUid, response.code);
1788
1789                    if (state.isVerificationComplete()) {
1790                        mPendingVerification.remove(verificationId);
1791
1792                        final InstallArgs args = state.getInstallArgs();
1793                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1794
1795                        int ret;
1796                        if (state.isInstallAllowed()) {
1797                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1798                            broadcastPackageVerified(verificationId, originUri,
1799                                    response.code, state.getInstallArgs().getUser());
1800                            try {
1801                                ret = args.copyApk(mContainerService, true);
1802                            } catch (RemoteException e) {
1803                                Slog.e(TAG, "Could not contact the ContainerService");
1804                            }
1805                        } else {
1806                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1807                        }
1808
1809                        Trace.asyncTraceEnd(
1810                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1811
1812                        processPendingInstall(args, ret);
1813                        mHandler.sendEmptyMessage(MCS_UNBIND);
1814                    }
1815
1816                    break;
1817                }
1818                case START_INTENT_FILTER_VERIFICATIONS: {
1819                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1820                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1821                            params.replacing, params.pkg);
1822                    break;
1823                }
1824                case INTENT_FILTER_VERIFIED: {
1825                    final int verificationId = msg.arg1;
1826
1827                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1828                            verificationId);
1829                    if (state == null) {
1830                        Slog.w(TAG, "Invalid IntentFilter verification token "
1831                                + verificationId + " received");
1832                        break;
1833                    }
1834
1835                    final int userId = state.getUserId();
1836
1837                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1838                            "Processing IntentFilter verification with token:"
1839                            + verificationId + " and userId:" + userId);
1840
1841                    final IntentFilterVerificationResponse response =
1842                            (IntentFilterVerificationResponse) msg.obj;
1843
1844                    state.setVerifierResponse(response.callerUid, response.code);
1845
1846                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1847                            "IntentFilter verification with token:" + verificationId
1848                            + " and userId:" + userId
1849                            + " is settings verifier response with response code:"
1850                            + response.code);
1851
1852                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1853                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1854                                + response.getFailedDomainsString());
1855                    }
1856
1857                    if (state.isVerificationComplete()) {
1858                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1859                    } else {
1860                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1861                                "IntentFilter verification with token:" + verificationId
1862                                + " was not said to be complete");
1863                    }
1864
1865                    break;
1866                }
1867                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1868                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1869                            mInstantAppResolverConnection,
1870                            (InstantAppRequest) msg.obj,
1871                            mInstantAppInstallerActivity,
1872                            mHandler);
1873                }
1874            }
1875        }
1876    }
1877
1878    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1879        @Override
1880        public void onGidsChanged(int appId, int userId) {
1881            mHandler.post(new Runnable() {
1882                @Override
1883                public void run() {
1884                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1885                }
1886            });
1887        }
1888        @Override
1889        public void onPermissionGranted(int uid, int userId) {
1890            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1891
1892            // Not critical; if this is lost, the application has to request again.
1893            synchronized (mPackages) {
1894                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1895            }
1896        }
1897        @Override
1898        public void onInstallPermissionGranted() {
1899            synchronized (mPackages) {
1900                scheduleWriteSettingsLocked();
1901            }
1902        }
1903        @Override
1904        public void onPermissionRevoked(int uid, int userId) {
1905            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1906
1907            synchronized (mPackages) {
1908                // Critical; after this call the application should never have the permission
1909                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1910            }
1911
1912            final int appId = UserHandle.getAppId(uid);
1913            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1914        }
1915        @Override
1916        public void onInstallPermissionRevoked() {
1917            synchronized (mPackages) {
1918                scheduleWriteSettingsLocked();
1919            }
1920        }
1921        @Override
1922        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1923            synchronized (mPackages) {
1924                for (int userId : updatedUserIds) {
1925                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1926                }
1927            }
1928        }
1929        @Override
1930        public void onInstallPermissionUpdated() {
1931            synchronized (mPackages) {
1932                scheduleWriteSettingsLocked();
1933            }
1934        }
1935        @Override
1936        public void onPermissionRemoved() {
1937            synchronized (mPackages) {
1938                mSettings.writeLPr();
1939            }
1940        }
1941    };
1942
1943    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1944            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1945            boolean launchedForRestore, String installerPackage,
1946            IPackageInstallObserver2 installObserver) {
1947        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1948            // Send the removed broadcasts
1949            if (res.removedInfo != null) {
1950                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1951            }
1952
1953            // Now that we successfully installed the package, grant runtime
1954            // permissions if requested before broadcasting the install. Also
1955            // for legacy apps in permission review mode we clear the permission
1956            // review flag which is used to emulate runtime permissions for
1957            // legacy apps.
1958            if (grantPermissions) {
1959                final int callingUid = Binder.getCallingUid();
1960                mPermissionManager.grantRequestedRuntimePermissions(
1961                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1962                        mPermissionCallback);
1963            }
1964
1965            final boolean update = res.removedInfo != null
1966                    && res.removedInfo.removedPackage != null;
1967            final String installerPackageName =
1968                    res.installerPackageName != null
1969                            ? res.installerPackageName
1970                            : res.removedInfo != null
1971                                    ? res.removedInfo.installerPackageName
1972                                    : null;
1973
1974            // If this is the first time we have child packages for a disabled privileged
1975            // app that had no children, we grant requested runtime permissions to the new
1976            // children if the parent on the system image had them already granted.
1977            if (res.pkg.parentPackage != null) {
1978                final int callingUid = Binder.getCallingUid();
1979                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1980                        res.pkg, callingUid, mPermissionCallback);
1981            }
1982
1983            synchronized (mPackages) {
1984                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1985            }
1986
1987            final String packageName = res.pkg.applicationInfo.packageName;
1988
1989            // Determine the set of users who are adding this package for
1990            // the first time vs. those who are seeing an update.
1991            int[] firstUserIds = EMPTY_INT_ARRAY;
1992            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1993            int[] updateUserIds = EMPTY_INT_ARRAY;
1994            int[] instantUserIds = EMPTY_INT_ARRAY;
1995            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1996            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1997            for (int newUser : res.newUsers) {
1998                final boolean isInstantApp = ps.getInstantApp(newUser);
1999                if (allNewUsers) {
2000                    if (isInstantApp) {
2001                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2002                    } else {
2003                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2004                    }
2005                    continue;
2006                }
2007                boolean isNew = true;
2008                for (int origUser : res.origUsers) {
2009                    if (origUser == newUser) {
2010                        isNew = false;
2011                        break;
2012                    }
2013                }
2014                if (isNew) {
2015                    if (isInstantApp) {
2016                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2017                    } else {
2018                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2019                    }
2020                } else {
2021                    if (isInstantApp) {
2022                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2023                    } else {
2024                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2025                    }
2026                }
2027            }
2028
2029            // Send installed broadcasts if the package is not a static shared lib.
2030            if (res.pkg.staticSharedLibName == null) {
2031                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2032
2033                // Send added for users that see the package for the first time
2034                // sendPackageAddedForNewUsers also deals with system apps
2035                int appId = UserHandle.getAppId(res.uid);
2036                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2037                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2038                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2039
2040                // Send added for users that don't see the package for the first time
2041                Bundle extras = new Bundle(1);
2042                extras.putInt(Intent.EXTRA_UID, res.uid);
2043                if (update) {
2044                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2045                }
2046                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2047                        extras, 0 /*flags*/,
2048                        null /*targetPackage*/, null /*finishedReceiver*/,
2049                        updateUserIds, instantUserIds);
2050                if (installerPackageName != null) {
2051                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2052                            extras, 0 /*flags*/,
2053                            installerPackageName, null /*finishedReceiver*/,
2054                            updateUserIds, instantUserIds);
2055                }
2056
2057                // Send replaced for users that don't see the package for the first time
2058                if (update) {
2059                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2060                            packageName, extras, 0 /*flags*/,
2061                            null /*targetPackage*/, null /*finishedReceiver*/,
2062                            updateUserIds, instantUserIds);
2063                    if (installerPackageName != null) {
2064                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2065                                extras, 0 /*flags*/,
2066                                installerPackageName, null /*finishedReceiver*/,
2067                                updateUserIds, instantUserIds);
2068                    }
2069                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2070                            null /*package*/, null /*extras*/, 0 /*flags*/,
2071                            packageName /*targetPackage*/,
2072                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2073                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2074                    // First-install and we did a restore, so we're responsible for the
2075                    // first-launch broadcast.
2076                    if (DEBUG_BACKUP) {
2077                        Slog.i(TAG, "Post-restore of " + packageName
2078                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2079                    }
2080                    sendFirstLaunchBroadcast(packageName, installerPackage,
2081                            firstUserIds, firstInstantUserIds);
2082                }
2083
2084                // Send broadcast package appeared if forward locked/external for all users
2085                // treat asec-hosted packages like removable media on upgrade
2086                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2087                    if (DEBUG_INSTALL) {
2088                        Slog.i(TAG, "upgrading pkg " + res.pkg
2089                                + " is ASEC-hosted -> AVAILABLE");
2090                    }
2091                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2092                    ArrayList<String> pkgList = new ArrayList<>(1);
2093                    pkgList.add(packageName);
2094                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2095                }
2096            }
2097
2098            // Work that needs to happen on first install within each user
2099            if (firstUserIds != null && firstUserIds.length > 0) {
2100                synchronized (mPackages) {
2101                    for (int userId : firstUserIds) {
2102                        // If this app is a browser and it's newly-installed for some
2103                        // users, clear any default-browser state in those users. The
2104                        // app's nature doesn't depend on the user, so we can just check
2105                        // its browser nature in any user and generalize.
2106                        if (packageIsBrowser(packageName, userId)) {
2107                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2108                        }
2109
2110                        // We may also need to apply pending (restored) runtime
2111                        // permission grants within these users.
2112                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2113                    }
2114                }
2115            }
2116
2117            if (allNewUsers && !update) {
2118                notifyPackageAdded(packageName);
2119            }
2120
2121            // Log current value of "unknown sources" setting
2122            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2123                    getUnknownSourcesSettings());
2124
2125            // Remove the replaced package's older resources safely now
2126            // We delete after a gc for applications  on sdcard.
2127            if (res.removedInfo != null && res.removedInfo.args != null) {
2128                Runtime.getRuntime().gc();
2129                synchronized (mInstallLock) {
2130                    res.removedInfo.args.doPostDeleteLI(true);
2131                }
2132            } else {
2133                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2134                // and not block here.
2135                VMRuntime.getRuntime().requestConcurrentGC();
2136            }
2137
2138            // Notify DexManager that the package was installed for new users.
2139            // The updated users should already be indexed and the package code paths
2140            // should not change.
2141            // Don't notify the manager for ephemeral apps as they are not expected to
2142            // survive long enough to benefit of background optimizations.
2143            for (int userId : firstUserIds) {
2144                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2145                // There's a race currently where some install events may interleave with an uninstall.
2146                // This can lead to package info being null (b/36642664).
2147                if (info != null) {
2148                    mDexManager.notifyPackageInstalled(info, userId);
2149                }
2150            }
2151        }
2152
2153        // If someone is watching installs - notify them
2154        if (installObserver != null) {
2155            try {
2156                Bundle extras = extrasForInstallResult(res);
2157                installObserver.onPackageInstalled(res.name, res.returnCode,
2158                        res.returnMsg, extras);
2159            } catch (RemoteException e) {
2160                Slog.i(TAG, "Observer no longer exists.");
2161            }
2162        }
2163    }
2164
2165    private StorageEventListener mStorageListener = new StorageEventListener() {
2166        @Override
2167        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2168            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2169                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2170                    final String volumeUuid = vol.getFsUuid();
2171
2172                    // Clean up any users or apps that were removed or recreated
2173                    // while this volume was missing
2174                    sUserManager.reconcileUsers(volumeUuid);
2175                    reconcileApps(volumeUuid);
2176
2177                    // Clean up any install sessions that expired or were
2178                    // cancelled while this volume was missing
2179                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2180
2181                    loadPrivatePackages(vol);
2182
2183                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2184                    unloadPrivatePackages(vol);
2185                }
2186            }
2187        }
2188
2189        @Override
2190        public void onVolumeForgotten(String fsUuid) {
2191            if (TextUtils.isEmpty(fsUuid)) {
2192                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2193                return;
2194            }
2195
2196            // Remove any apps installed on the forgotten volume
2197            synchronized (mPackages) {
2198                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2199                for (PackageSetting ps : packages) {
2200                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2201                    deletePackageVersioned(new VersionedPackage(ps.name,
2202                            PackageManager.VERSION_CODE_HIGHEST),
2203                            new LegacyPackageDeleteObserver(null).getBinder(),
2204                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2205                    // Try very hard to release any references to this package
2206                    // so we don't risk the system server being killed due to
2207                    // open FDs
2208                    AttributeCache.instance().removePackage(ps.name);
2209                }
2210
2211                mSettings.onVolumeForgotten(fsUuid);
2212                mSettings.writeLPr();
2213            }
2214        }
2215    };
2216
2217    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2218        Bundle extras = null;
2219        switch (res.returnCode) {
2220            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2221                extras = new Bundle();
2222                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2223                        res.origPermission);
2224                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2225                        res.origPackage);
2226                break;
2227            }
2228            case PackageManager.INSTALL_SUCCEEDED: {
2229                extras = new Bundle();
2230                extras.putBoolean(Intent.EXTRA_REPLACING,
2231                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2232                break;
2233            }
2234        }
2235        return extras;
2236    }
2237
2238    void scheduleWriteSettingsLocked() {
2239        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2240            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2241        }
2242    }
2243
2244    void scheduleWritePackageListLocked(int userId) {
2245        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2246            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2247            msg.arg1 = userId;
2248            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2249        }
2250    }
2251
2252    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2253        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2254        scheduleWritePackageRestrictionsLocked(userId);
2255    }
2256
2257    void scheduleWritePackageRestrictionsLocked(int userId) {
2258        final int[] userIds = (userId == UserHandle.USER_ALL)
2259                ? sUserManager.getUserIds() : new int[]{userId};
2260        for (int nextUserId : userIds) {
2261            if (!sUserManager.exists(nextUserId)) return;
2262            mDirtyUsers.add(nextUserId);
2263            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2264                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2265            }
2266        }
2267    }
2268
2269    public static PackageManagerService main(Context context, Installer installer,
2270            boolean factoryTest, boolean onlyCore) {
2271        // Self-check for initial settings.
2272        PackageManagerServiceCompilerMapping.checkProperties();
2273
2274        PackageManagerService m = new PackageManagerService(context, installer,
2275                factoryTest, onlyCore);
2276        m.enableSystemUserPackages();
2277        ServiceManager.addService("package", m);
2278        final PackageManagerNative pmn = m.new PackageManagerNative();
2279        ServiceManager.addService("package_native", pmn);
2280        return m;
2281    }
2282
2283    private void enableSystemUserPackages() {
2284        if (!UserManager.isSplitSystemUser()) {
2285            return;
2286        }
2287        // For system user, enable apps based on the following conditions:
2288        // - app is whitelisted or belong to one of these groups:
2289        //   -- system app which has no launcher icons
2290        //   -- system app which has INTERACT_ACROSS_USERS permission
2291        //   -- system IME app
2292        // - app is not in the blacklist
2293        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2294        Set<String> enableApps = new ArraySet<>();
2295        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2296                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2297                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2298        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2299        enableApps.addAll(wlApps);
2300        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2301                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2302        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2303        enableApps.removeAll(blApps);
2304        Log.i(TAG, "Applications installed for system user: " + enableApps);
2305        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2306                UserHandle.SYSTEM);
2307        final int allAppsSize = allAps.size();
2308        synchronized (mPackages) {
2309            for (int i = 0; i < allAppsSize; i++) {
2310                String pName = allAps.get(i);
2311                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2312                // Should not happen, but we shouldn't be failing if it does
2313                if (pkgSetting == null) {
2314                    continue;
2315                }
2316                boolean install = enableApps.contains(pName);
2317                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2318                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2319                            + " for system user");
2320                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2321                }
2322            }
2323            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2324        }
2325    }
2326
2327    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2328        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2329                Context.DISPLAY_SERVICE);
2330        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2331    }
2332
2333    /**
2334     * Requests that files preopted on a secondary system partition be copied to the data partition
2335     * if possible.  Note that the actual copying of the files is accomplished by init for security
2336     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2337     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2338     */
2339    private static void requestCopyPreoptedFiles() {
2340        final int WAIT_TIME_MS = 100;
2341        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2342        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2343            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2344            // We will wait for up to 100 seconds.
2345            final long timeStart = SystemClock.uptimeMillis();
2346            final long timeEnd = timeStart + 100 * 1000;
2347            long timeNow = timeStart;
2348            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2349                try {
2350                    Thread.sleep(WAIT_TIME_MS);
2351                } catch (InterruptedException e) {
2352                    // Do nothing
2353                }
2354                timeNow = SystemClock.uptimeMillis();
2355                if (timeNow > timeEnd) {
2356                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2357                    Slog.wtf(TAG, "cppreopt did not finish!");
2358                    break;
2359                }
2360            }
2361
2362            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2363        }
2364    }
2365
2366    public PackageManagerService(Context context, Installer installer,
2367            boolean factoryTest, boolean onlyCore) {
2368        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2369        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2370        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2371                SystemClock.uptimeMillis());
2372
2373        if (mSdkVersion <= 0) {
2374            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2375        }
2376
2377        mContext = context;
2378
2379        mFactoryTest = factoryTest;
2380        mOnlyCore = onlyCore;
2381        mMetrics = new DisplayMetrics();
2382        mInstaller = installer;
2383
2384        // Create sub-components that provide services / data. Order here is important.
2385        synchronized (mInstallLock) {
2386        synchronized (mPackages) {
2387            // Expose private service for system components to use.
2388            LocalServices.addService(
2389                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2390            sUserManager = new UserManagerService(context, this,
2391                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2392            mPermissionManager = PermissionManagerService.create(context,
2393                    new DefaultPermissionGrantedCallback() {
2394                        @Override
2395                        public void onDefaultRuntimePermissionsGranted(int userId) {
2396                            synchronized(mPackages) {
2397                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2398                            }
2399                        }
2400                    }, mPackages /*externalLock*/);
2401            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2402            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2403        }
2404        }
2405        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2410                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2411        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2412                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2413        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2414                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2415        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2416                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2417        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2418                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2419
2420        String separateProcesses = SystemProperties.get("debug.separate_processes");
2421        if (separateProcesses != null && separateProcesses.length() > 0) {
2422            if ("*".equals(separateProcesses)) {
2423                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2424                mSeparateProcesses = null;
2425                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2426            } else {
2427                mDefParseFlags = 0;
2428                mSeparateProcesses = separateProcesses.split(",");
2429                Slog.w(TAG, "Running with debug.separate_processes: "
2430                        + separateProcesses);
2431            }
2432        } else {
2433            mDefParseFlags = 0;
2434            mSeparateProcesses = null;
2435        }
2436
2437        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2438                "*dexopt*");
2439        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2440                installer, mInstallLock);
2441        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2442                dexManagerListener);
2443        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2444        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2445
2446        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2447                FgThread.get().getLooper());
2448
2449        getDefaultDisplayMetrics(context, mMetrics);
2450
2451        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2452        SystemConfig systemConfig = SystemConfig.getInstance();
2453        mAvailableFeatures = systemConfig.getAvailableFeatures();
2454        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2455
2456        mProtectedPackages = new ProtectedPackages(mContext);
2457
2458        synchronized (mInstallLock) {
2459        // writer
2460        synchronized (mPackages) {
2461            mHandlerThread = new ServiceThread(TAG,
2462                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2463            mHandlerThread.start();
2464            mHandler = new PackageHandler(mHandlerThread.getLooper());
2465            mProcessLoggingHandler = new ProcessLoggingHandler();
2466            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2467            mInstantAppRegistry = new InstantAppRegistry(this);
2468
2469            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2470            final int builtInLibCount = libConfig.size();
2471            for (int i = 0; i < builtInLibCount; i++) {
2472                String name = libConfig.keyAt(i);
2473                String path = libConfig.valueAt(i);
2474                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2475                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2476            }
2477
2478            SELinuxMMAC.readInstallPolicy();
2479
2480            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2481            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2482            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2483
2484            // Clean up orphaned packages for which the code path doesn't exist
2485            // and they are an update to a system app - caused by bug/32321269
2486            final int packageSettingCount = mSettings.mPackages.size();
2487            for (int i = packageSettingCount - 1; i >= 0; i--) {
2488                PackageSetting ps = mSettings.mPackages.valueAt(i);
2489                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2490                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2491                    mSettings.mPackages.removeAt(i);
2492                    mSettings.enableSystemPackageLPw(ps.name);
2493                }
2494            }
2495
2496            if (mFirstBoot) {
2497                requestCopyPreoptedFiles();
2498            }
2499
2500            String customResolverActivity = Resources.getSystem().getString(
2501                    R.string.config_customResolverActivity);
2502            if (TextUtils.isEmpty(customResolverActivity)) {
2503                customResolverActivity = null;
2504            } else {
2505                mCustomResolverComponentName = ComponentName.unflattenFromString(
2506                        customResolverActivity);
2507            }
2508
2509            long startTime = SystemClock.uptimeMillis();
2510
2511            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2512                    startTime);
2513
2514            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2515            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2516
2517            if (bootClassPath == null) {
2518                Slog.w(TAG, "No BOOTCLASSPATH found!");
2519            }
2520
2521            if (systemServerClassPath == null) {
2522                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2523            }
2524
2525            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2526
2527            final VersionInfo ver = mSettings.getInternalVersion();
2528            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2529            if (mIsUpgrade) {
2530                logCriticalInfo(Log.INFO,
2531                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2532            }
2533
2534            // when upgrading from pre-M, promote system app permissions from install to runtime
2535            mPromoteSystemApps =
2536                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2537
2538            // When upgrading from pre-N, we need to handle package extraction like first boot,
2539            // as there is no profiling data available.
2540            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2541
2542            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2543
2544            // save off the names of pre-existing system packages prior to scanning; we don't
2545            // want to automatically grant runtime permissions for new system apps
2546            if (mPromoteSystemApps) {
2547                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2548                while (pkgSettingIter.hasNext()) {
2549                    PackageSetting ps = pkgSettingIter.next();
2550                    if (isSystemApp(ps)) {
2551                        mExistingSystemPackages.add(ps.name);
2552                    }
2553                }
2554            }
2555
2556            mCacheDir = preparePackageParserCache(mIsUpgrade);
2557
2558            // Set flag to monitor and not change apk file paths when
2559            // scanning install directories.
2560            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2561
2562            if (mIsUpgrade || mFirstBoot) {
2563                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2564            }
2565
2566            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2567            // For security and version matching reason, only consider
2568            // overlay packages if they reside in the right directory.
2569            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2570                    mDefParseFlags
2571                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2572                    scanFlags
2573                    | SCAN_AS_SYSTEM
2574                    | SCAN_AS_VENDOR,
2575                    0);
2576            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2577                    mDefParseFlags
2578                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2579                    scanFlags
2580                    | SCAN_AS_SYSTEM
2581                    | SCAN_AS_PRODUCT,
2582                    0);
2583
2584            mParallelPackageParserCallback.findStaticOverlayPackages();
2585
2586            // Find base frameworks (resource packages without code).
2587            scanDirTracedLI(frameworkDir,
2588                    mDefParseFlags
2589                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2590                    scanFlags
2591                    | SCAN_NO_DEX
2592                    | SCAN_AS_SYSTEM
2593                    | SCAN_AS_PRIVILEGED,
2594                    0);
2595
2596            // Collect privileged system packages.
2597            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2598            scanDirTracedLI(privilegedAppDir,
2599                    mDefParseFlags
2600                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2601                    scanFlags
2602                    | SCAN_AS_SYSTEM
2603                    | SCAN_AS_PRIVILEGED,
2604                    0);
2605
2606            // Collect ordinary system packages.
2607            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2608            scanDirTracedLI(systemAppDir,
2609                    mDefParseFlags
2610                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2611                    scanFlags
2612                    | SCAN_AS_SYSTEM,
2613                    0);
2614
2615            // Collect privileged vendor packages.
2616            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2617            try {
2618                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2619            } catch (IOException e) {
2620                // failed to look up canonical path, continue with original one
2621            }
2622            scanDirTracedLI(privilegedVendorAppDir,
2623                    mDefParseFlags
2624                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2625                    scanFlags
2626                    | SCAN_AS_SYSTEM
2627                    | SCAN_AS_VENDOR
2628                    | SCAN_AS_PRIVILEGED,
2629                    0);
2630
2631            // Collect ordinary vendor packages.
2632            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2633            try {
2634                vendorAppDir = vendorAppDir.getCanonicalFile();
2635            } catch (IOException e) {
2636                // failed to look up canonical path, continue with original one
2637            }
2638            scanDirTracedLI(vendorAppDir,
2639                    mDefParseFlags
2640                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2641                    scanFlags
2642                    | SCAN_AS_SYSTEM
2643                    | SCAN_AS_VENDOR,
2644                    0);
2645
2646            // Collect privileged odm packages. /odm is another vendor partition
2647            // other than /vendor.
2648            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2649                        "priv-app");
2650            try {
2651                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2652            } catch (IOException e) {
2653                // failed to look up canonical path, continue with original one
2654            }
2655            scanDirTracedLI(privilegedOdmAppDir,
2656                    mDefParseFlags
2657                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2658                    scanFlags
2659                    | SCAN_AS_SYSTEM
2660                    | SCAN_AS_VENDOR
2661                    | SCAN_AS_PRIVILEGED,
2662                    0);
2663
2664            // Collect ordinary odm packages. /odm is another vendor partition
2665            // other than /vendor.
2666            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2667            try {
2668                odmAppDir = odmAppDir.getCanonicalFile();
2669            } catch (IOException e) {
2670                // failed to look up canonical path, continue with original one
2671            }
2672            scanDirTracedLI(odmAppDir,
2673                    mDefParseFlags
2674                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2675                    scanFlags
2676                    | SCAN_AS_SYSTEM
2677                    | SCAN_AS_VENDOR,
2678                    0);
2679
2680            // Collect all OEM packages.
2681            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2682            scanDirTracedLI(oemAppDir,
2683                    mDefParseFlags
2684                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2685                    scanFlags
2686                    | SCAN_AS_SYSTEM
2687                    | SCAN_AS_OEM,
2688                    0);
2689
2690            // Collected privileged product packages.
2691            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2692            try {
2693                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2694            } catch (IOException e) {
2695                // failed to look up canonical path, continue with original one
2696            }
2697            scanDirTracedLI(privilegedProductAppDir,
2698                    mDefParseFlags
2699                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2700                    scanFlags
2701                    | SCAN_AS_SYSTEM
2702                    | SCAN_AS_PRODUCT
2703                    | SCAN_AS_PRIVILEGED,
2704                    0);
2705
2706            // Collect ordinary product packages.
2707            File productAppDir = new File(Environment.getProductDirectory(), "app");
2708            try {
2709                productAppDir = productAppDir.getCanonicalFile();
2710            } catch (IOException e) {
2711                // failed to look up canonical path, continue with original one
2712            }
2713            scanDirTracedLI(productAppDir,
2714                    mDefParseFlags
2715                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2716                    scanFlags
2717                    | SCAN_AS_SYSTEM
2718                    | SCAN_AS_PRODUCT,
2719                    0);
2720
2721            // Prune any system packages that no longer exist.
2722            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2723            // Stub packages must either be replaced with full versions in the /data
2724            // partition or be disabled.
2725            final List<String> stubSystemApps = new ArrayList<>();
2726            if (!mOnlyCore) {
2727                // do this first before mucking with mPackages for the "expecting better" case
2728                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2729                while (pkgIterator.hasNext()) {
2730                    final PackageParser.Package pkg = pkgIterator.next();
2731                    if (pkg.isStub) {
2732                        stubSystemApps.add(pkg.packageName);
2733                    }
2734                }
2735
2736                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2737                while (psit.hasNext()) {
2738                    PackageSetting ps = psit.next();
2739
2740                    /*
2741                     * If this is not a system app, it can't be a
2742                     * disable system app.
2743                     */
2744                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2745                        continue;
2746                    }
2747
2748                    /*
2749                     * If the package is scanned, it's not erased.
2750                     */
2751                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2752                    if (scannedPkg != null) {
2753                        /*
2754                         * If the system app is both scanned and in the
2755                         * disabled packages list, then it must have been
2756                         * added via OTA. Remove it from the currently
2757                         * scanned package so the previously user-installed
2758                         * application can be scanned.
2759                         */
2760                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2761                            logCriticalInfo(Log.WARN,
2762                                    "Expecting better updated system app for " + ps.name
2763                                    + "; removing system app.  Last known"
2764                                    + " codePath=" + ps.codePathString
2765                                    + ", versionCode=" + ps.versionCode
2766                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2767                            removePackageLI(scannedPkg, true);
2768                            mExpectingBetter.put(ps.name, ps.codePath);
2769                        }
2770
2771                        continue;
2772                    }
2773
2774                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2775                        psit.remove();
2776                        logCriticalInfo(Log.WARN, "System package " + ps.name
2777                                + " no longer exists; it's data will be wiped");
2778                        // Actual deletion of code and data will be handled by later
2779                        // reconciliation step
2780                    } else {
2781                        // we still have a disabled system package, but, it still might have
2782                        // been removed. check the code path still exists and check there's
2783                        // still a package. the latter can happen if an OTA keeps the same
2784                        // code path, but, changes the package name.
2785                        final PackageSetting disabledPs =
2786                                mSettings.getDisabledSystemPkgLPr(ps.name);
2787                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2788                                || disabledPs.pkg == null) {
2789                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2790                        }
2791                    }
2792                }
2793            }
2794
2795            //delete tmp files
2796            deleteTempPackageFiles();
2797
2798            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2799
2800            // Remove any shared userIDs that have no associated packages
2801            mSettings.pruneSharedUsersLPw();
2802            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2803            final int systemPackagesCount = mPackages.size();
2804            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2805                    + " ms, packageCount: " + systemPackagesCount
2806                    + " , timePerPackage: "
2807                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2808                    + " , cached: " + cachedSystemApps);
2809            if (mIsUpgrade && systemPackagesCount > 0) {
2810                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2811                        ((int) systemScanTime) / systemPackagesCount);
2812            }
2813            if (!mOnlyCore) {
2814                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2815                        SystemClock.uptimeMillis());
2816                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2817
2818                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2819                        | PackageParser.PARSE_FORWARD_LOCK,
2820                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2821
2822                // Remove disable package settings for updated system apps that were
2823                // removed via an OTA. If the update is no longer present, remove the
2824                // app completely. Otherwise, revoke their system privileges.
2825                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2826                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2827                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2828                    final String msg;
2829                    if (deletedPkg == null) {
2830                        // should have found an update, but, we didn't; remove everything
2831                        msg = "Updated system package " + deletedAppName
2832                                + " no longer exists; removing its data";
2833                        // Actual deletion of code and data will be handled by later
2834                        // reconciliation step
2835                    } else {
2836                        // found an update; revoke system privileges
2837                        msg = "Updated system package + " + deletedAppName
2838                                + " no longer exists; revoking system privileges";
2839
2840                        // Don't do anything if a stub is removed from the system image. If
2841                        // we were to remove the uncompressed version from the /data partition,
2842                        // this is where it'd be done.
2843
2844                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2845                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2846                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2847                    }
2848                    logCriticalInfo(Log.WARN, msg);
2849                }
2850
2851                /*
2852                 * Make sure all system apps that we expected to appear on
2853                 * the userdata partition actually showed up. If they never
2854                 * appeared, crawl back and revive the system version.
2855                 */
2856                for (int i = 0; i < mExpectingBetter.size(); i++) {
2857                    final String packageName = mExpectingBetter.keyAt(i);
2858                    if (!mPackages.containsKey(packageName)) {
2859                        final File scanFile = mExpectingBetter.valueAt(i);
2860
2861                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2862                                + " but never showed up; reverting to system");
2863
2864                        final @ParseFlags int reparseFlags;
2865                        final @ScanFlags int rescanFlags;
2866                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2867                            reparseFlags =
2868                                    mDefParseFlags |
2869                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2870                            rescanFlags =
2871                                    scanFlags
2872                                    | SCAN_AS_SYSTEM
2873                                    | SCAN_AS_PRIVILEGED;
2874                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2875                            reparseFlags =
2876                                    mDefParseFlags |
2877                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2878                            rescanFlags =
2879                                    scanFlags
2880                                    | SCAN_AS_SYSTEM;
2881                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2882                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2883                            reparseFlags =
2884                                    mDefParseFlags |
2885                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2886                            rescanFlags =
2887                                    scanFlags
2888                                    | SCAN_AS_SYSTEM
2889                                    | SCAN_AS_VENDOR
2890                                    | SCAN_AS_PRIVILEGED;
2891                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2892                                || FileUtils.contains(odmAppDir, scanFile)) {
2893                            reparseFlags =
2894                                    mDefParseFlags |
2895                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2896                            rescanFlags =
2897                                    scanFlags
2898                                    | SCAN_AS_SYSTEM
2899                                    | SCAN_AS_VENDOR;
2900                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2901                            reparseFlags =
2902                                    mDefParseFlags |
2903                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2904                            rescanFlags =
2905                                    scanFlags
2906                                    | SCAN_AS_SYSTEM
2907                                    | SCAN_AS_OEM;
2908                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2909                            reparseFlags =
2910                                    mDefParseFlags |
2911                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2912                            rescanFlags =
2913                                    scanFlags
2914                                    | SCAN_AS_SYSTEM
2915                                    | SCAN_AS_PRODUCT
2916                                    | SCAN_AS_PRIVILEGED;
2917                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2918                            reparseFlags =
2919                                    mDefParseFlags |
2920                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2921                            rescanFlags =
2922                                    scanFlags
2923                                    | SCAN_AS_SYSTEM
2924                                    | SCAN_AS_PRODUCT;
2925                        } else {
2926                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2927                            continue;
2928                        }
2929
2930                        mSettings.enableSystemPackageLPw(packageName);
2931
2932                        try {
2933                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2934                        } catch (PackageManagerException e) {
2935                            Slog.e(TAG, "Failed to parse original system package: "
2936                                    + e.getMessage());
2937                        }
2938                    }
2939                }
2940
2941                // Uncompress and install any stubbed system applications.
2942                // This must be done last to ensure all stubs are replaced or disabled.
2943                decompressSystemApplications(stubSystemApps, scanFlags);
2944
2945                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2946                                - cachedSystemApps;
2947
2948                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2949                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2950                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2951                        + " ms, packageCount: " + dataPackagesCount
2952                        + " , timePerPackage: "
2953                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2954                        + " , cached: " + cachedNonSystemApps);
2955                if (mIsUpgrade && dataPackagesCount > 0) {
2956                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2957                            ((int) dataScanTime) / dataPackagesCount);
2958                }
2959            }
2960            mExpectingBetter.clear();
2961
2962            // Resolve the storage manager.
2963            mStorageManagerPackage = getStorageManagerPackageName();
2964
2965            // Resolve protected action filters. Only the setup wizard is allowed to
2966            // have a high priority filter for these actions.
2967            mSetupWizardPackage = getSetupWizardPackageName();
2968            if (mProtectedFilters.size() > 0) {
2969                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2970                    Slog.i(TAG, "No setup wizard;"
2971                        + " All protected intents capped to priority 0");
2972                }
2973                for (ActivityIntentInfo filter : mProtectedFilters) {
2974                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2975                        if (DEBUG_FILTERS) {
2976                            Slog.i(TAG, "Found setup wizard;"
2977                                + " allow priority " + filter.getPriority() + ";"
2978                                + " package: " + filter.activity.info.packageName
2979                                + " activity: " + filter.activity.className
2980                                + " priority: " + filter.getPriority());
2981                        }
2982                        // skip setup wizard; allow it to keep the high priority filter
2983                        continue;
2984                    }
2985                    if (DEBUG_FILTERS) {
2986                        Slog.i(TAG, "Protected action; cap priority to 0;"
2987                                + " package: " + filter.activity.info.packageName
2988                                + " activity: " + filter.activity.className
2989                                + " origPrio: " + filter.getPriority());
2990                    }
2991                    filter.setPriority(0);
2992                }
2993            }
2994
2995            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
2996
2997            mDeferProtectedFilters = false;
2998            mProtectedFilters.clear();
2999
3000            // Now that we know all of the shared libraries, update all clients to have
3001            // the correct library paths.
3002            updateAllSharedLibrariesLPw(null);
3003
3004            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3005                // NOTE: We ignore potential failures here during a system scan (like
3006                // the rest of the commands above) because there's precious little we
3007                // can do about it. A settings error is reported, though.
3008                final List<String> changedAbiCodePath =
3009                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3010                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3011                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3012                        final String codePathString = changedAbiCodePath.get(i);
3013                        try {
3014                            mInstaller.rmdex(codePathString,
3015                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3016                        } catch (InstallerException ignored) {
3017                        }
3018                    }
3019                }
3020                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3021                // SELinux domain.
3022                setting.fixSeInfoLocked();
3023            }
3024
3025            // Now that we know all the packages we are keeping,
3026            // read and update their last usage times.
3027            mPackageUsage.read(mPackages);
3028            mCompilerStats.read();
3029
3030            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3031                    SystemClock.uptimeMillis());
3032            Slog.i(TAG, "Time to scan packages: "
3033                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3034                    + " seconds");
3035
3036            // If the platform SDK has changed since the last time we booted,
3037            // we need to re-grant app permission to catch any new ones that
3038            // appear.  This is really a hack, and means that apps can in some
3039            // cases get permissions that the user didn't initially explicitly
3040            // allow...  it would be nice to have some better way to handle
3041            // this situation.
3042            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3043            if (sdkUpdated) {
3044                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3045                        + mSdkVersion + "; regranting permissions for internal storage");
3046            }
3047            mPermissionManager.updateAllPermissions(
3048                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3049                    mPermissionCallback);
3050            ver.sdkVersion = mSdkVersion;
3051
3052            // If this is the first boot or an update from pre-M, and it is a normal
3053            // boot, then we need to initialize the default preferred apps across
3054            // all defined users.
3055            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3056                for (UserInfo user : sUserManager.getUsers(true)) {
3057                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3058                    applyFactoryDefaultBrowserLPw(user.id);
3059                    primeDomainVerificationsLPw(user.id);
3060                }
3061            }
3062
3063            // Prepare storage for system user really early during boot,
3064            // since core system apps like SettingsProvider and SystemUI
3065            // can't wait for user to start
3066            final int storageFlags;
3067            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3068                storageFlags = StorageManager.FLAG_STORAGE_DE;
3069            } else {
3070                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3071            }
3072            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3073                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3074                    true /* onlyCoreApps */);
3075            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3076                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3077                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3078                traceLog.traceBegin("AppDataFixup");
3079                try {
3080                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3081                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3082                } catch (InstallerException e) {
3083                    Slog.w(TAG, "Trouble fixing GIDs", e);
3084                }
3085                traceLog.traceEnd();
3086
3087                traceLog.traceBegin("AppDataPrepare");
3088                if (deferPackages == null || deferPackages.isEmpty()) {
3089                    return;
3090                }
3091                int count = 0;
3092                for (String pkgName : deferPackages) {
3093                    PackageParser.Package pkg = null;
3094                    synchronized (mPackages) {
3095                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3096                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3097                            pkg = ps.pkg;
3098                        }
3099                    }
3100                    if (pkg != null) {
3101                        synchronized (mInstallLock) {
3102                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3103                                    true /* maybeMigrateAppData */);
3104                        }
3105                        count++;
3106                    }
3107                }
3108                traceLog.traceEnd();
3109                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3110            }, "prepareAppData");
3111
3112            // If this is first boot after an OTA, and a normal boot, then
3113            // we need to clear code cache directories.
3114            // Note that we do *not* clear the application profiles. These remain valid
3115            // across OTAs and are used to drive profile verification (post OTA) and
3116            // profile compilation (without waiting to collect a fresh set of profiles).
3117            if (mIsUpgrade && !onlyCore) {
3118                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3119                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3120                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3121                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3122                        // No apps are running this early, so no need to freeze
3123                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3124                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3125                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3126                    }
3127                }
3128                ver.fingerprint = Build.FINGERPRINT;
3129            }
3130
3131            checkDefaultBrowser();
3132
3133            // clear only after permissions and other defaults have been updated
3134            mExistingSystemPackages.clear();
3135            mPromoteSystemApps = false;
3136
3137            // All the changes are done during package scanning.
3138            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3139
3140            // can downgrade to reader
3141            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3142            mSettings.writeLPr();
3143            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3144            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3145                    SystemClock.uptimeMillis());
3146
3147            if (!mOnlyCore) {
3148                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3149                mRequiredInstallerPackage = getRequiredInstallerLPr();
3150                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3151                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3152                if (mIntentFilterVerifierComponent != null) {
3153                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3154                            mIntentFilterVerifierComponent);
3155                } else {
3156                    mIntentFilterVerifier = null;
3157                }
3158                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3159                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3160                        SharedLibraryInfo.VERSION_UNDEFINED);
3161                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3162                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3163                        SharedLibraryInfo.VERSION_UNDEFINED);
3164            } else {
3165                mRequiredVerifierPackage = null;
3166                mRequiredInstallerPackage = null;
3167                mRequiredUninstallerPackage = null;
3168                mIntentFilterVerifierComponent = null;
3169                mIntentFilterVerifier = null;
3170                mServicesSystemSharedLibraryPackageName = null;
3171                mSharedSystemSharedLibraryPackageName = null;
3172            }
3173
3174            mInstallerService = new PackageInstallerService(context, this);
3175            final Pair<ComponentName, String> instantAppResolverComponent =
3176                    getInstantAppResolverLPr();
3177            if (instantAppResolverComponent != null) {
3178                if (DEBUG_INSTANT) {
3179                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3180                }
3181                mInstantAppResolverConnection = new InstantAppResolverConnection(
3182                        mContext, instantAppResolverComponent.first,
3183                        instantAppResolverComponent.second);
3184                mInstantAppResolverSettingsComponent =
3185                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3186            } else {
3187                mInstantAppResolverConnection = null;
3188                mInstantAppResolverSettingsComponent = null;
3189            }
3190            updateInstantAppInstallerLocked(null);
3191
3192            // Read and update the usage of dex files.
3193            // Do this at the end of PM init so that all the packages have their
3194            // data directory reconciled.
3195            // At this point we know the code paths of the packages, so we can validate
3196            // the disk file and build the internal cache.
3197            // The usage file is expected to be small so loading and verifying it
3198            // should take a fairly small time compare to the other activities (e.g. package
3199            // scanning).
3200            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3201            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3202            for (int userId : currentUserIds) {
3203                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3204            }
3205            mDexManager.load(userPackages);
3206            if (mIsUpgrade) {
3207                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3208                        (int) (SystemClock.uptimeMillis() - startTime));
3209            }
3210        } // synchronized (mPackages)
3211        } // synchronized (mInstallLock)
3212
3213        // Now after opening every single application zip, make sure they
3214        // are all flushed.  Not really needed, but keeps things nice and
3215        // tidy.
3216        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3217        Runtime.getRuntime().gc();
3218        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3219
3220        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3221        FallbackCategoryProvider.loadFallbacks();
3222        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3223
3224        // The initial scanning above does many calls into installd while
3225        // holding the mPackages lock, but we're mostly interested in yelling
3226        // once we have a booted system.
3227        mInstaller.setWarnIfHeld(mPackages);
3228
3229        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3230    }
3231
3232    /**
3233     * Uncompress and install stub applications.
3234     * <p>In order to save space on the system partition, some applications are shipped in a
3235     * compressed form. In addition the compressed bits for the full application, the
3236     * system image contains a tiny stub comprised of only the Android manifest.
3237     * <p>During the first boot, attempt to uncompress and install the full application. If
3238     * the application can't be installed for any reason, disable the stub and prevent
3239     * uncompressing the full application during future boots.
3240     * <p>In order to forcefully attempt an installation of a full application, go to app
3241     * settings and enable the application.
3242     */
3243    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3244        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3245            final String pkgName = stubSystemApps.get(i);
3246            // skip if the system package is already disabled
3247            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3248                stubSystemApps.remove(i);
3249                continue;
3250            }
3251            // skip if the package isn't installed (?!); this should never happen
3252            final PackageParser.Package pkg = mPackages.get(pkgName);
3253            if (pkg == null) {
3254                stubSystemApps.remove(i);
3255                continue;
3256            }
3257            // skip if the package has been disabled by the user
3258            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3259            if (ps != null) {
3260                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3261                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3262                    stubSystemApps.remove(i);
3263                    continue;
3264                }
3265            }
3266
3267            if (DEBUG_COMPRESSION) {
3268                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3269            }
3270
3271            // uncompress the binary to its eventual destination on /data
3272            final File scanFile = decompressPackage(pkg);
3273            if (scanFile == null) {
3274                continue;
3275            }
3276
3277            // install the package to replace the stub on /system
3278            try {
3279                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3280                removePackageLI(pkg, true /*chatty*/);
3281                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3282                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3283                        UserHandle.USER_SYSTEM, "android");
3284                stubSystemApps.remove(i);
3285                continue;
3286            } catch (PackageManagerException e) {
3287                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3288            }
3289
3290            // any failed attempt to install the package will be cleaned up later
3291        }
3292
3293        // disable any stub still left; these failed to install the full application
3294        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3295            final String pkgName = stubSystemApps.get(i);
3296            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3297            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3298                    UserHandle.USER_SYSTEM, "android");
3299            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3300        }
3301    }
3302
3303    /**
3304     * Decompresses the given package on the system image onto
3305     * the /data partition.
3306     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3307     */
3308    private File decompressPackage(PackageParser.Package pkg) {
3309        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3310        if (compressedFiles == null || compressedFiles.length == 0) {
3311            if (DEBUG_COMPRESSION) {
3312                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3313            }
3314            return null;
3315        }
3316        final File dstCodePath =
3317                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3318        int ret = PackageManager.INSTALL_SUCCEEDED;
3319        try {
3320            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3321            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3322            for (File srcFile : compressedFiles) {
3323                final String srcFileName = srcFile.getName();
3324                final String dstFileName = srcFileName.substring(
3325                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3326                final File dstFile = new File(dstCodePath, dstFileName);
3327                ret = decompressFile(srcFile, dstFile);
3328                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3329                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3330                            + "; pkg: " + pkg.packageName
3331                            + ", file: " + dstFileName);
3332                    break;
3333                }
3334            }
3335        } catch (ErrnoException e) {
3336            logCriticalInfo(Log.ERROR, "Failed to decompress"
3337                    + "; pkg: " + pkg.packageName
3338                    + ", err: " + e.errno);
3339        }
3340        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3341            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3342            NativeLibraryHelper.Handle handle = null;
3343            try {
3344                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3345                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3346                        null /*abiOverride*/);
3347            } catch (IOException e) {
3348                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3349                        + "; pkg: " + pkg.packageName);
3350                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3351            } finally {
3352                IoUtils.closeQuietly(handle);
3353            }
3354        }
3355        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3356            if (dstCodePath == null || !dstCodePath.exists()) {
3357                return null;
3358            }
3359            removeCodePathLI(dstCodePath);
3360            return null;
3361        }
3362
3363        return dstCodePath;
3364    }
3365
3366    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3367        // we're only interested in updating the installer appliction when 1) it's not
3368        // already set or 2) the modified package is the installer
3369        if (mInstantAppInstallerActivity != null
3370                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3371                        .equals(modifiedPackage)) {
3372            return;
3373        }
3374        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3375    }
3376
3377    private static File preparePackageParserCache(boolean isUpgrade) {
3378        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3379            return null;
3380        }
3381
3382        // Disable package parsing on eng builds to allow for faster incremental development.
3383        if (Build.IS_ENG) {
3384            return null;
3385        }
3386
3387        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3388            Slog.i(TAG, "Disabling package parser cache due to system property.");
3389            return null;
3390        }
3391
3392        // The base directory for the package parser cache lives under /data/system/.
3393        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3394                "package_cache");
3395        if (cacheBaseDir == null) {
3396            return null;
3397        }
3398
3399        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3400        // This also serves to "GC" unused entries when the package cache version changes (which
3401        // can only happen during upgrades).
3402        if (isUpgrade) {
3403            FileUtils.deleteContents(cacheBaseDir);
3404        }
3405
3406
3407        // Return the versioned package cache directory. This is something like
3408        // "/data/system/package_cache/1"
3409        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3410
3411        if (cacheDir == null) {
3412            // Something went wrong. Attempt to delete everything and return.
3413            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3414            FileUtils.deleteContentsAndDir(cacheBaseDir);
3415            return null;
3416        }
3417
3418        // The following is a workaround to aid development on non-numbered userdebug
3419        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3420        // the system partition is newer.
3421        //
3422        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3423        // that starts with "eng." to signify that this is an engineering build and not
3424        // destined for release.
3425        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3426            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3427
3428            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3429            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3430            // in general and should not be used for production changes. In this specific case,
3431            // we know that they will work.
3432            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3433            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3434                FileUtils.deleteContents(cacheBaseDir);
3435                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3436            }
3437        }
3438
3439        return cacheDir;
3440    }
3441
3442    @Override
3443    public boolean isFirstBoot() {
3444        // allow instant applications
3445        return mFirstBoot;
3446    }
3447
3448    @Override
3449    public boolean isOnlyCoreApps() {
3450        // allow instant applications
3451        return mOnlyCore;
3452    }
3453
3454    @Override
3455    public boolean isUpgrade() {
3456        // allow instant applications
3457        // The system property allows testing ota flow when upgraded to the same image.
3458        return mIsUpgrade || SystemProperties.getBoolean(
3459                "persist.pm.mock-upgrade", false /* default */);
3460    }
3461
3462    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3463        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3464
3465        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3466                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3467                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3468        if (matches.size() == 1) {
3469            return matches.get(0).getComponentInfo().packageName;
3470        } else if (matches.size() == 0) {
3471            Log.e(TAG, "There should probably be a verifier, but, none were found");
3472            return null;
3473        }
3474        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3475    }
3476
3477    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3478        synchronized (mPackages) {
3479            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3480            if (libraryEntry == null) {
3481                throw new IllegalStateException("Missing required shared library:" + name);
3482            }
3483            return libraryEntry.apk;
3484        }
3485    }
3486
3487    private @NonNull String getRequiredInstallerLPr() {
3488        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3489        intent.addCategory(Intent.CATEGORY_DEFAULT);
3490        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3491
3492        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3493                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3494                UserHandle.USER_SYSTEM);
3495        if (matches.size() == 1) {
3496            ResolveInfo resolveInfo = matches.get(0);
3497            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3498                throw new RuntimeException("The installer must be a privileged app");
3499            }
3500            return matches.get(0).getComponentInfo().packageName;
3501        } else {
3502            throw new RuntimeException("There must be exactly one installer; found " + matches);
3503        }
3504    }
3505
3506    private @NonNull String getRequiredUninstallerLPr() {
3507        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3508        intent.addCategory(Intent.CATEGORY_DEFAULT);
3509        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3510
3511        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3512                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3513                UserHandle.USER_SYSTEM);
3514        if (resolveInfo == null ||
3515                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3516            throw new RuntimeException("There must be exactly one uninstaller; found "
3517                    + resolveInfo);
3518        }
3519        return resolveInfo.getComponentInfo().packageName;
3520    }
3521
3522    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3523        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3524
3525        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3526                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3527                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3528        ResolveInfo best = null;
3529        final int N = matches.size();
3530        for (int i = 0; i < N; i++) {
3531            final ResolveInfo cur = matches.get(i);
3532            final String packageName = cur.getComponentInfo().packageName;
3533            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3534                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3535                continue;
3536            }
3537
3538            if (best == null || cur.priority > best.priority) {
3539                best = cur;
3540            }
3541        }
3542
3543        if (best != null) {
3544            return best.getComponentInfo().getComponentName();
3545        }
3546        Slog.w(TAG, "Intent filter verifier not found");
3547        return null;
3548    }
3549
3550    @Override
3551    public @Nullable ComponentName getInstantAppResolverComponent() {
3552        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3553            return null;
3554        }
3555        synchronized (mPackages) {
3556            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3557            if (instantAppResolver == null) {
3558                return null;
3559            }
3560            return instantAppResolver.first;
3561        }
3562    }
3563
3564    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3565        final String[] packageArray =
3566                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3567        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3568            if (DEBUG_INSTANT) {
3569                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3570            }
3571            return null;
3572        }
3573
3574        final int callingUid = Binder.getCallingUid();
3575        final int resolveFlags =
3576                MATCH_DIRECT_BOOT_AWARE
3577                | MATCH_DIRECT_BOOT_UNAWARE
3578                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3579        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3580        final Intent resolverIntent = new Intent(actionName);
3581        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3582                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3583        final int N = resolvers.size();
3584        if (N == 0) {
3585            if (DEBUG_INSTANT) {
3586                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3587            }
3588            return null;
3589        }
3590
3591        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3592        for (int i = 0; i < N; i++) {
3593            final ResolveInfo info = resolvers.get(i);
3594
3595            if (info.serviceInfo == null) {
3596                continue;
3597            }
3598
3599            final String packageName = info.serviceInfo.packageName;
3600            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3601                if (DEBUG_INSTANT) {
3602                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3603                            + " pkg: " + packageName + ", info:" + info);
3604                }
3605                continue;
3606            }
3607
3608            if (DEBUG_INSTANT) {
3609                Slog.v(TAG, "Ephemeral resolver found;"
3610                        + " pkg: " + packageName + ", info:" + info);
3611            }
3612            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3613        }
3614        if (DEBUG_INSTANT) {
3615            Slog.v(TAG, "Ephemeral resolver NOT found");
3616        }
3617        return null;
3618    }
3619
3620    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3621        String[] orderedActions = Build.IS_ENG
3622                ? new String[]{
3623                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3624                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3625                : new String[]{
3626                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3627
3628        final int resolveFlags =
3629                MATCH_DIRECT_BOOT_AWARE
3630                        | MATCH_DIRECT_BOOT_UNAWARE
3631                        | Intent.FLAG_IGNORE_EPHEMERAL
3632                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3633        final Intent intent = new Intent();
3634        intent.addCategory(Intent.CATEGORY_DEFAULT);
3635        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3636        List<ResolveInfo> matches = null;
3637        for (String action : orderedActions) {
3638            intent.setAction(action);
3639            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3640                    resolveFlags, UserHandle.USER_SYSTEM);
3641            if (matches.isEmpty()) {
3642                if (DEBUG_INSTANT) {
3643                    Slog.d(TAG, "Instant App installer not found with " + action);
3644                }
3645            } else {
3646                break;
3647            }
3648        }
3649        Iterator<ResolveInfo> iter = matches.iterator();
3650        while (iter.hasNext()) {
3651            final ResolveInfo rInfo = iter.next();
3652            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3653            if (ps != null) {
3654                final PermissionsState permissionsState = ps.getPermissionsState();
3655                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3656                        || Build.IS_ENG) {
3657                    continue;
3658                }
3659            }
3660            iter.remove();
3661        }
3662        if (matches.size() == 0) {
3663            return null;
3664        } else if (matches.size() == 1) {
3665            return (ActivityInfo) matches.get(0).getComponentInfo();
3666        } else {
3667            throw new RuntimeException(
3668                    "There must be at most one ephemeral installer; found " + matches);
3669        }
3670    }
3671
3672    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3673            @NonNull ComponentName resolver) {
3674        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3675                .addCategory(Intent.CATEGORY_DEFAULT)
3676                .setPackage(resolver.getPackageName());
3677        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3678        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3679                UserHandle.USER_SYSTEM);
3680        if (matches.isEmpty()) {
3681            return null;
3682        }
3683        return matches.get(0).getComponentInfo().getComponentName();
3684    }
3685
3686    private void primeDomainVerificationsLPw(int userId) {
3687        if (DEBUG_DOMAIN_VERIFICATION) {
3688            Slog.d(TAG, "Priming domain verifications in user " + userId);
3689        }
3690
3691        SystemConfig systemConfig = SystemConfig.getInstance();
3692        ArraySet<String> packages = systemConfig.getLinkedApps();
3693
3694        for (String packageName : packages) {
3695            PackageParser.Package pkg = mPackages.get(packageName);
3696            if (pkg != null) {
3697                if (!pkg.isSystem()) {
3698                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3699                    continue;
3700                }
3701
3702                ArraySet<String> domains = null;
3703                for (PackageParser.Activity a : pkg.activities) {
3704                    for (ActivityIntentInfo filter : a.intents) {
3705                        if (hasValidDomains(filter)) {
3706                            if (domains == null) {
3707                                domains = new ArraySet<String>();
3708                            }
3709                            domains.addAll(filter.getHostsList());
3710                        }
3711                    }
3712                }
3713
3714                if (domains != null && domains.size() > 0) {
3715                    if (DEBUG_DOMAIN_VERIFICATION) {
3716                        Slog.v(TAG, "      + " + packageName);
3717                    }
3718                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3719                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3720                    // and then 'always' in the per-user state actually used for intent resolution.
3721                    final IntentFilterVerificationInfo ivi;
3722                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3723                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3724                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3725                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3726                } else {
3727                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3728                            + "' does not handle web links");
3729                }
3730            } else {
3731                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3732            }
3733        }
3734
3735        scheduleWritePackageRestrictionsLocked(userId);
3736        scheduleWriteSettingsLocked();
3737    }
3738
3739    private void applyFactoryDefaultBrowserLPw(int userId) {
3740        // The default browser app's package name is stored in a string resource,
3741        // with a product-specific overlay used for vendor customization.
3742        String browserPkg = mContext.getResources().getString(
3743                com.android.internal.R.string.default_browser);
3744        if (!TextUtils.isEmpty(browserPkg)) {
3745            // non-empty string => required to be a known package
3746            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3747            if (ps == null) {
3748                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3749                browserPkg = null;
3750            } else {
3751                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3752            }
3753        }
3754
3755        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3756        // default.  If there's more than one, just leave everything alone.
3757        if (browserPkg == null) {
3758            calculateDefaultBrowserLPw(userId);
3759        }
3760    }
3761
3762    private void calculateDefaultBrowserLPw(int userId) {
3763        List<String> allBrowsers = resolveAllBrowserApps(userId);
3764        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3765        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3766    }
3767
3768    private List<String> resolveAllBrowserApps(int userId) {
3769        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3770        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3771                PackageManager.MATCH_ALL, userId);
3772
3773        final int count = list.size();
3774        List<String> result = new ArrayList<String>(count);
3775        for (int i=0; i<count; i++) {
3776            ResolveInfo info = list.get(i);
3777            if (info.activityInfo == null
3778                    || !info.handleAllWebDataURI
3779                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3780                    || result.contains(info.activityInfo.packageName)) {
3781                continue;
3782            }
3783            result.add(info.activityInfo.packageName);
3784        }
3785
3786        return result;
3787    }
3788
3789    private boolean packageIsBrowser(String packageName, int userId) {
3790        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3791                PackageManager.MATCH_ALL, userId);
3792        final int N = list.size();
3793        for (int i = 0; i < N; i++) {
3794            ResolveInfo info = list.get(i);
3795            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3796                return true;
3797            }
3798        }
3799        return false;
3800    }
3801
3802    private void checkDefaultBrowser() {
3803        final int myUserId = UserHandle.myUserId();
3804        final String packageName = getDefaultBrowserPackageName(myUserId);
3805        if (packageName != null) {
3806            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3807            if (info == null) {
3808                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3809                synchronized (mPackages) {
3810                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3811                }
3812            }
3813        }
3814    }
3815
3816    @Override
3817    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3818            throws RemoteException {
3819        try {
3820            return super.onTransact(code, data, reply, flags);
3821        } catch (RuntimeException e) {
3822            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3823                Slog.wtf(TAG, "Package Manager Crash", e);
3824            }
3825            throw e;
3826        }
3827    }
3828
3829    static int[] appendInts(int[] cur, int[] add) {
3830        if (add == null) return cur;
3831        if (cur == null) return add;
3832        final int N = add.length;
3833        for (int i=0; i<N; i++) {
3834            cur = appendInt(cur, add[i]);
3835        }
3836        return cur;
3837    }
3838
3839    /**
3840     * Returns whether or not a full application can see an instant application.
3841     * <p>
3842     * Currently, there are three cases in which this can occur:
3843     * <ol>
3844     * <li>The calling application is a "special" process. Special processes
3845     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3846     * <li>The calling application has the permission
3847     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3848     * <li>The calling application is the default launcher on the
3849     *     system partition.</li>
3850     * </ol>
3851     */
3852    private boolean canViewInstantApps(int callingUid, int userId) {
3853        if (callingUid < Process.FIRST_APPLICATION_UID) {
3854            return true;
3855        }
3856        if (mContext.checkCallingOrSelfPermission(
3857                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3858            return true;
3859        }
3860        if (mContext.checkCallingOrSelfPermission(
3861                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3862            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3863            if (homeComponent != null
3864                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3865                return true;
3866            }
3867        }
3868        return false;
3869    }
3870
3871    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3872        if (!sUserManager.exists(userId)) return null;
3873        if (ps == null) {
3874            return null;
3875        }
3876        final int callingUid = Binder.getCallingUid();
3877        // Filter out ephemeral app metadata:
3878        //   * The system/shell/root can see metadata for any app
3879        //   * An installed app can see metadata for 1) other installed apps
3880        //     and 2) ephemeral apps that have explicitly interacted with it
3881        //   * Ephemeral apps can only see their own data and exposed installed apps
3882        //   * Holding a signature permission allows seeing instant apps
3883        if (filterAppAccessLPr(ps, callingUid, userId)) {
3884            return null;
3885        }
3886
3887        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3888                && ps.isSystem()) {
3889            flags |= MATCH_ANY_USER;
3890        }
3891
3892        final PackageUserState state = ps.readUserState(userId);
3893        PackageParser.Package p = ps.pkg;
3894        if (p != null) {
3895            final PermissionsState permissionsState = ps.getPermissionsState();
3896
3897            // Compute GIDs only if requested
3898            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3899                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3900            // Compute granted permissions only if package has requested permissions
3901            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3902                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3903
3904            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3905                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3906
3907            if (packageInfo == null) {
3908                return null;
3909            }
3910
3911            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3912                    resolveExternalPackageNameLPr(p);
3913
3914            return packageInfo;
3915        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3916            PackageInfo pi = new PackageInfo();
3917            pi.packageName = ps.name;
3918            pi.setLongVersionCode(ps.versionCode);
3919            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3920            pi.firstInstallTime = ps.firstInstallTime;
3921            pi.lastUpdateTime = ps.lastUpdateTime;
3922
3923            ApplicationInfo ai = new ApplicationInfo();
3924            ai.packageName = ps.name;
3925            ai.uid = UserHandle.getUid(userId, ps.appId);
3926            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3927            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3928            ai.versionCode = ps.versionCode;
3929            ai.flags = ps.pkgFlags;
3930            ai.privateFlags = ps.pkgPrivateFlags;
3931            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3932
3933            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3934                    + ps.name + "]. Provides a minimum info.");
3935            return pi;
3936        } else {
3937            return null;
3938        }
3939    }
3940
3941    @Override
3942    public void checkPackageStartable(String packageName, int userId) {
3943        final int callingUid = Binder.getCallingUid();
3944        if (getInstantAppPackageName(callingUid) != null) {
3945            throw new SecurityException("Instant applications don't have access to this method");
3946        }
3947        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3948        synchronized (mPackages) {
3949            final PackageSetting ps = mSettings.mPackages.get(packageName);
3950            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3951                throw new SecurityException("Package " + packageName + " was not found!");
3952            }
3953
3954            if (!ps.getInstalled(userId)) {
3955                throw new SecurityException(
3956                        "Package " + packageName + " was not installed for user " + userId + "!");
3957            }
3958
3959            if (mSafeMode && !ps.isSystem()) {
3960                throw new SecurityException("Package " + packageName + " not a system app!");
3961            }
3962
3963            if (mFrozenPackages.contains(packageName)) {
3964                throw new SecurityException("Package " + packageName + " is currently frozen!");
3965            }
3966
3967            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3968                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3969            }
3970        }
3971    }
3972
3973    @Override
3974    public boolean isPackageAvailable(String packageName, int userId) {
3975        if (!sUserManager.exists(userId)) return false;
3976        final int callingUid = Binder.getCallingUid();
3977        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3978                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3979        synchronized (mPackages) {
3980            PackageParser.Package p = mPackages.get(packageName);
3981            if (p != null) {
3982                final PackageSetting ps = (PackageSetting) p.mExtras;
3983                if (filterAppAccessLPr(ps, callingUid, userId)) {
3984                    return false;
3985                }
3986                if (ps != null) {
3987                    final PackageUserState state = ps.readUserState(userId);
3988                    if (state != null) {
3989                        return PackageParser.isAvailable(state);
3990                    }
3991                }
3992            }
3993        }
3994        return false;
3995    }
3996
3997    @Override
3998    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3999        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
4000                flags, Binder.getCallingUid(), userId);
4001    }
4002
4003    @Override
4004    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4005            int flags, int userId) {
4006        return getPackageInfoInternal(versionedPackage.getPackageName(),
4007                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4008    }
4009
4010    /**
4011     * Important: The provided filterCallingUid is used exclusively to filter out packages
4012     * that can be seen based on user state. It's typically the original caller uid prior
4013     * to clearing. Because it can only be provided by trusted code, it's value can be
4014     * trusted and will be used as-is; unlike userId which will be validated by this method.
4015     */
4016    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4017            int flags, int filterCallingUid, int userId) {
4018        if (!sUserManager.exists(userId)) return null;
4019        flags = updateFlagsForPackage(flags, userId, packageName);
4020        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4021                false /* requireFullPermission */, false /* checkShell */, "get package info");
4022
4023        // reader
4024        synchronized (mPackages) {
4025            // Normalize package name to handle renamed packages and static libs
4026            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4027
4028            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4029            if (matchFactoryOnly) {
4030                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4031                if (ps != null) {
4032                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4033                        return null;
4034                    }
4035                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4036                        return null;
4037                    }
4038                    return generatePackageInfo(ps, flags, userId);
4039                }
4040            }
4041
4042            PackageParser.Package p = mPackages.get(packageName);
4043            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4044                return null;
4045            }
4046            if (DEBUG_PACKAGE_INFO)
4047                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4048            if (p != null) {
4049                final PackageSetting ps = (PackageSetting) p.mExtras;
4050                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4051                    return null;
4052                }
4053                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4054                    return null;
4055                }
4056                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4057            }
4058            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4059                final PackageSetting ps = mSettings.mPackages.get(packageName);
4060                if (ps == null) return null;
4061                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4062                    return null;
4063                }
4064                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4065                    return null;
4066                }
4067                return generatePackageInfo(ps, flags, userId);
4068            }
4069        }
4070        return null;
4071    }
4072
4073    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4074        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4075            return true;
4076        }
4077        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4078            return true;
4079        }
4080        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4081            return true;
4082        }
4083        return false;
4084    }
4085
4086    private boolean isComponentVisibleToInstantApp(
4087            @Nullable ComponentName component, @ComponentType int type) {
4088        if (type == TYPE_ACTIVITY) {
4089            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4090            return activity != null
4091                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4092                    : false;
4093        } else if (type == TYPE_RECEIVER) {
4094            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4095            return activity != null
4096                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4097                    : false;
4098        } else if (type == TYPE_SERVICE) {
4099            final PackageParser.Service service = mServices.mServices.get(component);
4100            return service != null
4101                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4102                    : false;
4103        } else if (type == TYPE_PROVIDER) {
4104            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4105            return provider != null
4106                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4107                    : false;
4108        } else if (type == TYPE_UNKNOWN) {
4109            return isComponentVisibleToInstantApp(component);
4110        }
4111        return false;
4112    }
4113
4114    /**
4115     * Returns whether or not access to the application should be filtered.
4116     * <p>
4117     * Access may be limited based upon whether the calling or target applications
4118     * are instant applications.
4119     *
4120     * @see #canAccessInstantApps(int)
4121     */
4122    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4123            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4124        // if we're in an isolated process, get the real calling UID
4125        if (Process.isIsolated(callingUid)) {
4126            callingUid = mIsolatedOwners.get(callingUid);
4127        }
4128        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4129        final boolean callerIsInstantApp = instantAppPkgName != null;
4130        if (ps == null) {
4131            if (callerIsInstantApp) {
4132                // pretend the application exists, but, needs to be filtered
4133                return true;
4134            }
4135            return false;
4136        }
4137        // if the target and caller are the same application, don't filter
4138        if (isCallerSameApp(ps.name, callingUid)) {
4139            return false;
4140        }
4141        if (callerIsInstantApp) {
4142            // request for a specific component; if it hasn't been explicitly exposed through
4143            // property or instrumentation target, filter
4144            if (component != null) {
4145                final PackageParser.Instrumentation instrumentation =
4146                        mInstrumentation.get(component);
4147                if (instrumentation != null
4148                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4149                    return false;
4150                }
4151                return !isComponentVisibleToInstantApp(component, componentType);
4152            }
4153            // request for application; if no components have been explicitly exposed, filter
4154            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4155        }
4156        if (ps.getInstantApp(userId)) {
4157            // caller can see all components of all instant applications, don't filter
4158            if (canViewInstantApps(callingUid, userId)) {
4159                return false;
4160            }
4161            // request for a specific instant application component, filter
4162            if (component != null) {
4163                return true;
4164            }
4165            // request for an instant application; if the caller hasn't been granted access, filter
4166            return !mInstantAppRegistry.isInstantAccessGranted(
4167                    userId, UserHandle.getAppId(callingUid), ps.appId);
4168        }
4169        return false;
4170    }
4171
4172    /**
4173     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4174     */
4175    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4176        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4177    }
4178
4179    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4180            int flags) {
4181        // Callers can access only the libs they depend on, otherwise they need to explicitly
4182        // ask for the shared libraries given the caller is allowed to access all static libs.
4183        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4184            // System/shell/root get to see all static libs
4185            final int appId = UserHandle.getAppId(uid);
4186            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4187                    || appId == Process.ROOT_UID) {
4188                return false;
4189            }
4190        }
4191
4192        // No package means no static lib as it is always on internal storage
4193        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4194            return false;
4195        }
4196
4197        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4198                ps.pkg.staticSharedLibVersion);
4199        if (libEntry == null) {
4200            return false;
4201        }
4202
4203        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4204        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4205        if (uidPackageNames == null) {
4206            return true;
4207        }
4208
4209        for (String uidPackageName : uidPackageNames) {
4210            if (ps.name.equals(uidPackageName)) {
4211                return false;
4212            }
4213            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4214            if (uidPs != null) {
4215                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4216                        libEntry.info.getName());
4217                if (index < 0) {
4218                    continue;
4219                }
4220                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4221                    return false;
4222                }
4223            }
4224        }
4225        return true;
4226    }
4227
4228    @Override
4229    public String[] currentToCanonicalPackageNames(String[] names) {
4230        final int callingUid = Binder.getCallingUid();
4231        if (getInstantAppPackageName(callingUid) != null) {
4232            return names;
4233        }
4234        final String[] out = new String[names.length];
4235        // reader
4236        synchronized (mPackages) {
4237            final int callingUserId = UserHandle.getUserId(callingUid);
4238            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4239            for (int i=names.length-1; i>=0; i--) {
4240                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4241                boolean translateName = false;
4242                if (ps != null && ps.realName != null) {
4243                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4244                    translateName = !targetIsInstantApp
4245                            || canViewInstantApps
4246                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4247                                    UserHandle.getAppId(callingUid), ps.appId);
4248                }
4249                out[i] = translateName ? ps.realName : names[i];
4250            }
4251        }
4252        return out;
4253    }
4254
4255    @Override
4256    public String[] canonicalToCurrentPackageNames(String[] names) {
4257        final int callingUid = Binder.getCallingUid();
4258        if (getInstantAppPackageName(callingUid) != null) {
4259            return names;
4260        }
4261        final String[] out = new String[names.length];
4262        // reader
4263        synchronized (mPackages) {
4264            final int callingUserId = UserHandle.getUserId(callingUid);
4265            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4266            for (int i=names.length-1; i>=0; i--) {
4267                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4268                boolean translateName = false;
4269                if (cur != null) {
4270                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4271                    final boolean targetIsInstantApp =
4272                            ps != null && ps.getInstantApp(callingUserId);
4273                    translateName = !targetIsInstantApp
4274                            || canViewInstantApps
4275                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4276                                    UserHandle.getAppId(callingUid), ps.appId);
4277                }
4278                out[i] = translateName ? cur : names[i];
4279            }
4280        }
4281        return out;
4282    }
4283
4284    @Override
4285    public int getPackageUid(String packageName, int flags, int userId) {
4286        if (!sUserManager.exists(userId)) return -1;
4287        final int callingUid = Binder.getCallingUid();
4288        flags = updateFlagsForPackage(flags, userId, packageName);
4289        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4290                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4291
4292        // reader
4293        synchronized (mPackages) {
4294            final PackageParser.Package p = mPackages.get(packageName);
4295            if (p != null && p.isMatch(flags)) {
4296                PackageSetting ps = (PackageSetting) p.mExtras;
4297                if (filterAppAccessLPr(ps, callingUid, userId)) {
4298                    return -1;
4299                }
4300                return UserHandle.getUid(userId, p.applicationInfo.uid);
4301            }
4302            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4303                final PackageSetting ps = mSettings.mPackages.get(packageName);
4304                if (ps != null && ps.isMatch(flags)
4305                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4306                    return UserHandle.getUid(userId, ps.appId);
4307                }
4308            }
4309        }
4310
4311        return -1;
4312    }
4313
4314    @Override
4315    public int[] getPackageGids(String packageName, int flags, int userId) {
4316        if (!sUserManager.exists(userId)) return null;
4317        final int callingUid = Binder.getCallingUid();
4318        flags = updateFlagsForPackage(flags, userId, packageName);
4319        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4320                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4321
4322        // reader
4323        synchronized (mPackages) {
4324            final PackageParser.Package p = mPackages.get(packageName);
4325            if (p != null && p.isMatch(flags)) {
4326                PackageSetting ps = (PackageSetting) p.mExtras;
4327                if (filterAppAccessLPr(ps, callingUid, userId)) {
4328                    return null;
4329                }
4330                // TODO: Shouldn't this be checking for package installed state for userId and
4331                // return null?
4332                return ps.getPermissionsState().computeGids(userId);
4333            }
4334            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4335                final PackageSetting ps = mSettings.mPackages.get(packageName);
4336                if (ps != null && ps.isMatch(flags)
4337                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4338                    return ps.getPermissionsState().computeGids(userId);
4339                }
4340            }
4341        }
4342
4343        return null;
4344    }
4345
4346    @Override
4347    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4348        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4349    }
4350
4351    @Override
4352    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4353            int flags) {
4354        final List<PermissionInfo> permissionList =
4355                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4356        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4357    }
4358
4359    @Override
4360    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4361        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4362    }
4363
4364    @Override
4365    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4366        final List<PermissionGroupInfo> permissionList =
4367                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4368        return (permissionList == null)
4369                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4370    }
4371
4372    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4373            int filterCallingUid, int userId) {
4374        if (!sUserManager.exists(userId)) return null;
4375        PackageSetting ps = mSettings.mPackages.get(packageName);
4376        if (ps != null) {
4377            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4378                return null;
4379            }
4380            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4381                return null;
4382            }
4383            if (ps.pkg == null) {
4384                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4385                if (pInfo != null) {
4386                    return pInfo.applicationInfo;
4387                }
4388                return null;
4389            }
4390            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4391                    ps.readUserState(userId), userId);
4392            if (ai != null) {
4393                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4394            }
4395            return ai;
4396        }
4397        return null;
4398    }
4399
4400    @Override
4401    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4402        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4403    }
4404
4405    /**
4406     * Important: The provided filterCallingUid is used exclusively to filter out applications
4407     * that can be seen based on user state. It's typically the original caller uid prior
4408     * to clearing. Because it can only be provided by trusted code, it's value can be
4409     * trusted and will be used as-is; unlike userId which will be validated by this method.
4410     */
4411    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4412            int filterCallingUid, int userId) {
4413        if (!sUserManager.exists(userId)) return null;
4414        flags = updateFlagsForApplication(flags, userId, packageName);
4415        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4416                false /* requireFullPermission */, false /* checkShell */, "get application info");
4417
4418        // writer
4419        synchronized (mPackages) {
4420            // Normalize package name to handle renamed packages and static libs
4421            packageName = resolveInternalPackageNameLPr(packageName,
4422                    PackageManager.VERSION_CODE_HIGHEST);
4423
4424            PackageParser.Package p = mPackages.get(packageName);
4425            if (DEBUG_PACKAGE_INFO) Log.v(
4426                    TAG, "getApplicationInfo " + packageName
4427                    + ": " + p);
4428            if (p != null) {
4429                PackageSetting ps = mSettings.mPackages.get(packageName);
4430                if (ps == null) return null;
4431                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4432                    return null;
4433                }
4434                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4435                    return null;
4436                }
4437                // Note: isEnabledLP() does not apply here - always return info
4438                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4439                        p, flags, ps.readUserState(userId), userId);
4440                if (ai != null) {
4441                    ai.packageName = resolveExternalPackageNameLPr(p);
4442                }
4443                return ai;
4444            }
4445            if ("android".equals(packageName)||"system".equals(packageName)) {
4446                return mAndroidApplication;
4447            }
4448            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4449                // Already generates the external package name
4450                return generateApplicationInfoFromSettingsLPw(packageName,
4451                        flags, filterCallingUid, userId);
4452            }
4453        }
4454        return null;
4455    }
4456
4457    private String normalizePackageNameLPr(String packageName) {
4458        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4459        return normalizedPackageName != null ? normalizedPackageName : packageName;
4460    }
4461
4462    @Override
4463    public void deletePreloadsFileCache() {
4464        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4465            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4466        }
4467        File dir = Environment.getDataPreloadsFileCacheDirectory();
4468        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4469        FileUtils.deleteContents(dir);
4470    }
4471
4472    @Override
4473    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4474            final int storageFlags, final IPackageDataObserver observer) {
4475        mContext.enforceCallingOrSelfPermission(
4476                android.Manifest.permission.CLEAR_APP_CACHE, null);
4477        mHandler.post(() -> {
4478            boolean success = false;
4479            try {
4480                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4481                success = true;
4482            } catch (IOException e) {
4483                Slog.w(TAG, e);
4484            }
4485            if (observer != null) {
4486                try {
4487                    observer.onRemoveCompleted(null, success);
4488                } catch (RemoteException e) {
4489                    Slog.w(TAG, e);
4490                }
4491            }
4492        });
4493    }
4494
4495    @Override
4496    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4497            final int storageFlags, final IntentSender pi) {
4498        mContext.enforceCallingOrSelfPermission(
4499                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4500        mHandler.post(() -> {
4501            boolean success = false;
4502            try {
4503                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4504                success = true;
4505            } catch (IOException e) {
4506                Slog.w(TAG, e);
4507            }
4508            if (pi != null) {
4509                try {
4510                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4511                } catch (SendIntentException e) {
4512                    Slog.w(TAG, e);
4513                }
4514            }
4515        });
4516    }
4517
4518    /**
4519     * Blocking call to clear various types of cached data across the system
4520     * until the requested bytes are available.
4521     */
4522    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4523        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4524        final File file = storage.findPathForUuid(volumeUuid);
4525        if (file.getUsableSpace() >= bytes) return;
4526
4527        if (ENABLE_FREE_CACHE_V2) {
4528            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4529                    volumeUuid);
4530            final boolean aggressive = (storageFlags
4531                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4532            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4533
4534            // 1. Pre-flight to determine if we have any chance to succeed
4535            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4536            if (internalVolume && (aggressive || SystemProperties
4537                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4538                deletePreloadsFileCache();
4539                if (file.getUsableSpace() >= bytes) return;
4540            }
4541
4542            // 3. Consider parsed APK data (aggressive only)
4543            if (internalVolume && aggressive) {
4544                FileUtils.deleteContents(mCacheDir);
4545                if (file.getUsableSpace() >= bytes) return;
4546            }
4547
4548            // 4. Consider cached app data (above quotas)
4549            try {
4550                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4551                        Installer.FLAG_FREE_CACHE_V2);
4552            } catch (InstallerException ignored) {
4553            }
4554            if (file.getUsableSpace() >= bytes) return;
4555
4556            // 5. Consider shared libraries with refcount=0 and age>min cache period
4557            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4558                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4559                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4560                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4561                return;
4562            }
4563
4564            // 6. Consider dexopt output (aggressive only)
4565            // TODO: Implement
4566
4567            // 7. Consider installed instant apps unused longer than min cache period
4568            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4569                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4570                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4571                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4572                return;
4573            }
4574
4575            // 8. Consider cached app data (below quotas)
4576            try {
4577                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4578                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4579            } catch (InstallerException ignored) {
4580            }
4581            if (file.getUsableSpace() >= bytes) return;
4582
4583            // 9. Consider DropBox entries
4584            // TODO: Implement
4585
4586            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4587            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4588                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4589                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4590                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4591                return;
4592            }
4593        } else {
4594            try {
4595                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4596            } catch (InstallerException ignored) {
4597            }
4598            if (file.getUsableSpace() >= bytes) return;
4599        }
4600
4601        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4602    }
4603
4604    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4605            throws IOException {
4606        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4607        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4608
4609        List<VersionedPackage> packagesToDelete = null;
4610        final long now = System.currentTimeMillis();
4611
4612        synchronized (mPackages) {
4613            final int[] allUsers = sUserManager.getUserIds();
4614            final int libCount = mSharedLibraries.size();
4615            for (int i = 0; i < libCount; i++) {
4616                final LongSparseArray<SharedLibraryEntry> versionedLib
4617                        = mSharedLibraries.valueAt(i);
4618                if (versionedLib == null) {
4619                    continue;
4620                }
4621                final int versionCount = versionedLib.size();
4622                for (int j = 0; j < versionCount; j++) {
4623                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4624                    // Skip packages that are not static shared libs.
4625                    if (!libInfo.isStatic()) {
4626                        break;
4627                    }
4628                    // Important: We skip static shared libs used for some user since
4629                    // in such a case we need to keep the APK on the device. The check for
4630                    // a lib being used for any user is performed by the uninstall call.
4631                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4632                    // Resolve the package name - we use synthetic package names internally
4633                    final String internalPackageName = resolveInternalPackageNameLPr(
4634                            declaringPackage.getPackageName(),
4635                            declaringPackage.getLongVersionCode());
4636                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4637                    // Skip unused static shared libs cached less than the min period
4638                    // to prevent pruning a lib needed by a subsequently installed package.
4639                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4640                        continue;
4641                    }
4642                    if (packagesToDelete == null) {
4643                        packagesToDelete = new ArrayList<>();
4644                    }
4645                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4646                            declaringPackage.getLongVersionCode()));
4647                }
4648            }
4649        }
4650
4651        if (packagesToDelete != null) {
4652            final int packageCount = packagesToDelete.size();
4653            for (int i = 0; i < packageCount; i++) {
4654                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4655                // Delete the package synchronously (will fail of the lib used for any user).
4656                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4657                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4658                                == PackageManager.DELETE_SUCCEEDED) {
4659                    if (volume.getUsableSpace() >= neededSpace) {
4660                        return true;
4661                    }
4662                }
4663            }
4664        }
4665
4666        return false;
4667    }
4668
4669    /**
4670     * Update given flags based on encryption status of current user.
4671     */
4672    private int updateFlags(int flags, int userId) {
4673        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4674                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4675            // Caller expressed an explicit opinion about what encryption
4676            // aware/unaware components they want to see, so fall through and
4677            // give them what they want
4678        } else {
4679            // Caller expressed no opinion, so match based on user state
4680            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4681                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4682            } else {
4683                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4684            }
4685        }
4686        return flags;
4687    }
4688
4689    private UserManagerInternal getUserManagerInternal() {
4690        if (mUserManagerInternal == null) {
4691            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4692        }
4693        return mUserManagerInternal;
4694    }
4695
4696    private ActivityManagerInternal getActivityManagerInternal() {
4697        if (mActivityManagerInternal == null) {
4698            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4699        }
4700        return mActivityManagerInternal;
4701    }
4702
4703
4704    private DeviceIdleController.LocalService getDeviceIdleController() {
4705        if (mDeviceIdleController == null) {
4706            mDeviceIdleController =
4707                    LocalServices.getService(DeviceIdleController.LocalService.class);
4708        }
4709        return mDeviceIdleController;
4710    }
4711
4712    /**
4713     * Update given flags when being used to request {@link PackageInfo}.
4714     */
4715    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4716        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4717        boolean triaged = true;
4718        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4719                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4720            // Caller is asking for component details, so they'd better be
4721            // asking for specific encryption matching behavior, or be triaged
4722            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4723                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4724                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4725                triaged = false;
4726            }
4727        }
4728        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4729                | PackageManager.MATCH_SYSTEM_ONLY
4730                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4731            triaged = false;
4732        }
4733        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4734            mPermissionManager.enforceCrossUserPermission(
4735                    Binder.getCallingUid(), userId, false, false,
4736                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4737                    + Debug.getCallers(5));
4738        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4739                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4740            // If the caller wants all packages and has a restricted profile associated with it,
4741            // then match all users. This is to make sure that launchers that need to access work
4742            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4743            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4744            flags |= PackageManager.MATCH_ANY_USER;
4745        }
4746        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4747            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4748                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4749        }
4750        return updateFlags(flags, userId);
4751    }
4752
4753    /**
4754     * Update given flags when being used to request {@link ApplicationInfo}.
4755     */
4756    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4757        return updateFlagsForPackage(flags, userId, cookie);
4758    }
4759
4760    /**
4761     * Update given flags when being used to request {@link ComponentInfo}.
4762     */
4763    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4764        if (cookie instanceof Intent) {
4765            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4766                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4767            }
4768        }
4769
4770        boolean triaged = true;
4771        // Caller is asking for component details, so they'd better be
4772        // asking for specific encryption matching behavior, or be triaged
4773        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4774                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4775                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4776            triaged = false;
4777        }
4778        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4779            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4780                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4781        }
4782
4783        return updateFlags(flags, userId);
4784    }
4785
4786    /**
4787     * Update given intent when being used to request {@link ResolveInfo}.
4788     */
4789    private Intent updateIntentForResolve(Intent intent) {
4790        if (intent.getSelector() != null) {
4791            intent = intent.getSelector();
4792        }
4793        if (DEBUG_PREFERRED) {
4794            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4795        }
4796        return intent;
4797    }
4798
4799    /**
4800     * Update given flags when being used to request {@link ResolveInfo}.
4801     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4802     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4803     * flag set. However, this flag is only honoured in three circumstances:
4804     * <ul>
4805     * <li>when called from a system process</li>
4806     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4807     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4808     * action and a {@code android.intent.category.BROWSABLE} category</li>
4809     * </ul>
4810     */
4811    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4812        return updateFlagsForResolve(flags, userId, intent, callingUid,
4813                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4814    }
4815    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4816            boolean wantInstantApps) {
4817        return updateFlagsForResolve(flags, userId, intent, callingUid,
4818                wantInstantApps, false /*onlyExposedExplicitly*/);
4819    }
4820    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4821            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4822        // Safe mode means we shouldn't match any third-party components
4823        if (mSafeMode) {
4824            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4825        }
4826        if (getInstantAppPackageName(callingUid) != null) {
4827            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4828            if (onlyExposedExplicitly) {
4829                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4830            }
4831            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4832            flags |= PackageManager.MATCH_INSTANT;
4833        } else {
4834            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4835            final boolean allowMatchInstant = wantInstantApps
4836                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4837            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4838                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4839            if (!allowMatchInstant) {
4840                flags &= ~PackageManager.MATCH_INSTANT;
4841            }
4842        }
4843        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4844    }
4845
4846    @Override
4847    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4848        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4849    }
4850
4851    /**
4852     * Important: The provided filterCallingUid is used exclusively to filter out activities
4853     * that can be seen based on user state. It's typically the original caller uid prior
4854     * to clearing. Because it can only be provided by trusted code, it's value can be
4855     * trusted and will be used as-is; unlike userId which will be validated by this method.
4856     */
4857    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4858            int filterCallingUid, int userId) {
4859        if (!sUserManager.exists(userId)) return null;
4860        flags = updateFlagsForComponent(flags, userId, component);
4861
4862        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4863            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4864                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4865        }
4866
4867        synchronized (mPackages) {
4868            PackageParser.Activity a = mActivities.mActivities.get(component);
4869
4870            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4871            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4872                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4873                if (ps == null) return null;
4874                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4875                    return null;
4876                }
4877                return PackageParser.generateActivityInfo(
4878                        a, flags, ps.readUserState(userId), userId);
4879            }
4880            if (mResolveComponentName.equals(component)) {
4881                return PackageParser.generateActivityInfo(
4882                        mResolveActivity, flags, new PackageUserState(), userId);
4883            }
4884        }
4885        return null;
4886    }
4887
4888    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4889        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4890            return false;
4891        }
4892        final long token = Binder.clearCallingIdentity();
4893        try {
4894            final int callingUserId = UserHandle.getUserId(callingUid);
4895            if (ActivityManager.getCurrentUser() != callingUserId) {
4896                return false;
4897            }
4898            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4899        } finally {
4900            Binder.restoreCallingIdentity(token);
4901        }
4902    }
4903
4904    @Override
4905    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4906            String resolvedType) {
4907        synchronized (mPackages) {
4908            if (component.equals(mResolveComponentName)) {
4909                // The resolver supports EVERYTHING!
4910                return true;
4911            }
4912            final int callingUid = Binder.getCallingUid();
4913            final int callingUserId = UserHandle.getUserId(callingUid);
4914            PackageParser.Activity a = mActivities.mActivities.get(component);
4915            if (a == null) {
4916                return false;
4917            }
4918            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4919            if (ps == null) {
4920                return false;
4921            }
4922            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4923                return false;
4924            }
4925            for (int i=0; i<a.intents.size(); i++) {
4926                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4927                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4928                    return true;
4929                }
4930            }
4931            return false;
4932        }
4933    }
4934
4935    @Override
4936    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4937        if (!sUserManager.exists(userId)) return null;
4938        final int callingUid = Binder.getCallingUid();
4939        flags = updateFlagsForComponent(flags, userId, component);
4940        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4941                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4942        synchronized (mPackages) {
4943            PackageParser.Activity a = mReceivers.mActivities.get(component);
4944            if (DEBUG_PACKAGE_INFO) Log.v(
4945                TAG, "getReceiverInfo " + component + ": " + a);
4946            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4947                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4948                if (ps == null) return null;
4949                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4950                    return null;
4951                }
4952                return PackageParser.generateActivityInfo(
4953                        a, flags, ps.readUserState(userId), userId);
4954            }
4955        }
4956        return null;
4957    }
4958
4959    @Override
4960    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4961            int flags, int userId) {
4962        if (!sUserManager.exists(userId)) return null;
4963        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4964        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4965            return null;
4966        }
4967
4968        flags = updateFlagsForPackage(flags, userId, null);
4969
4970        final boolean canSeeStaticLibraries =
4971                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4972                        == PERMISSION_GRANTED
4973                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4974                        == PERMISSION_GRANTED
4975                || canRequestPackageInstallsInternal(packageName,
4976                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4977                        false  /* throwIfPermNotDeclared*/)
4978                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4979                        == PERMISSION_GRANTED;
4980
4981        synchronized (mPackages) {
4982            List<SharedLibraryInfo> result = null;
4983
4984            final int libCount = mSharedLibraries.size();
4985            for (int i = 0; i < libCount; i++) {
4986                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4987                if (versionedLib == null) {
4988                    continue;
4989                }
4990
4991                final int versionCount = versionedLib.size();
4992                for (int j = 0; j < versionCount; j++) {
4993                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4994                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4995                        break;
4996                    }
4997                    final long identity = Binder.clearCallingIdentity();
4998                    try {
4999                        PackageInfo packageInfo = getPackageInfoVersioned(
5000                                libInfo.getDeclaringPackage(), flags
5001                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5002                        if (packageInfo == null) {
5003                            continue;
5004                        }
5005                    } finally {
5006                        Binder.restoreCallingIdentity(identity);
5007                    }
5008
5009                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5010                            libInfo.getLongVersion(), libInfo.getType(),
5011                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5012                            flags, userId));
5013
5014                    if (result == null) {
5015                        result = new ArrayList<>();
5016                    }
5017                    result.add(resLibInfo);
5018                }
5019            }
5020
5021            return result != null ? new ParceledListSlice<>(result) : null;
5022        }
5023    }
5024
5025    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5026            SharedLibraryInfo libInfo, int flags, int userId) {
5027        List<VersionedPackage> versionedPackages = null;
5028        final int packageCount = mSettings.mPackages.size();
5029        for (int i = 0; i < packageCount; i++) {
5030            PackageSetting ps = mSettings.mPackages.valueAt(i);
5031
5032            if (ps == null) {
5033                continue;
5034            }
5035
5036            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5037                continue;
5038            }
5039
5040            final String libName = libInfo.getName();
5041            if (libInfo.isStatic()) {
5042                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5043                if (libIdx < 0) {
5044                    continue;
5045                }
5046                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5047                    continue;
5048                }
5049                if (versionedPackages == null) {
5050                    versionedPackages = new ArrayList<>();
5051                }
5052                // If the dependent is a static shared lib, use the public package name
5053                String dependentPackageName = ps.name;
5054                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5055                    dependentPackageName = ps.pkg.manifestPackageName;
5056                }
5057                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5058            } else if (ps.pkg != null) {
5059                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5060                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5061                    if (versionedPackages == null) {
5062                        versionedPackages = new ArrayList<>();
5063                    }
5064                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5065                }
5066            }
5067        }
5068
5069        return versionedPackages;
5070    }
5071
5072    @Override
5073    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5074        if (!sUserManager.exists(userId)) return null;
5075        final int callingUid = Binder.getCallingUid();
5076        flags = updateFlagsForComponent(flags, userId, component);
5077        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5078                false /* requireFullPermission */, false /* checkShell */, "get service info");
5079        synchronized (mPackages) {
5080            PackageParser.Service s = mServices.mServices.get(component);
5081            if (DEBUG_PACKAGE_INFO) Log.v(
5082                TAG, "getServiceInfo " + component + ": " + s);
5083            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5084                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5085                if (ps == null) return null;
5086                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5087                    return null;
5088                }
5089                return PackageParser.generateServiceInfo(
5090                        s, flags, ps.readUserState(userId), userId);
5091            }
5092        }
5093        return null;
5094    }
5095
5096    @Override
5097    public ProviderInfo getProviderInfo(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 provider info");
5103        synchronized (mPackages) {
5104            PackageParser.Provider p = mProviders.mProviders.get(component);
5105            if (DEBUG_PACKAGE_INFO) Log.v(
5106                TAG, "getProviderInfo " + component + ": " + p);
5107            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5108                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5109                if (ps == null) return null;
5110                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5111                    return null;
5112                }
5113                return PackageParser.generateProviderInfo(
5114                        p, flags, ps.readUserState(userId), userId);
5115            }
5116        }
5117        return null;
5118    }
5119
5120    @Override
5121    public String[] getSystemSharedLibraryNames() {
5122        // allow instant applications
5123        synchronized (mPackages) {
5124            Set<String> libs = null;
5125            final int libCount = mSharedLibraries.size();
5126            for (int i = 0; i < libCount; i++) {
5127                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5128                if (versionedLib == null) {
5129                    continue;
5130                }
5131                final int versionCount = versionedLib.size();
5132                for (int j = 0; j < versionCount; j++) {
5133                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5134                    if (!libEntry.info.isStatic()) {
5135                        if (libs == null) {
5136                            libs = new ArraySet<>();
5137                        }
5138                        libs.add(libEntry.info.getName());
5139                        break;
5140                    }
5141                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5142                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5143                            UserHandle.getUserId(Binder.getCallingUid()),
5144                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5145                        if (libs == null) {
5146                            libs = new ArraySet<>();
5147                        }
5148                        libs.add(libEntry.info.getName());
5149                        break;
5150                    }
5151                }
5152            }
5153
5154            if (libs != null) {
5155                String[] libsArray = new String[libs.size()];
5156                libs.toArray(libsArray);
5157                return libsArray;
5158            }
5159
5160            return null;
5161        }
5162    }
5163
5164    @Override
5165    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5166        // allow instant applications
5167        synchronized (mPackages) {
5168            return mServicesSystemSharedLibraryPackageName;
5169        }
5170    }
5171
5172    @Override
5173    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5174        // allow instant applications
5175        synchronized (mPackages) {
5176            return mSharedSystemSharedLibraryPackageName;
5177        }
5178    }
5179
5180    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5181        for (int i = userList.length - 1; i >= 0; --i) {
5182            final int userId = userList[i];
5183            // don't add instant app to the list of updates
5184            if (pkgSetting.getInstantApp(userId)) {
5185                continue;
5186            }
5187            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5188            if (changedPackages == null) {
5189                changedPackages = new SparseArray<>();
5190                mChangedPackages.put(userId, changedPackages);
5191            }
5192            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5193            if (sequenceNumbers == null) {
5194                sequenceNumbers = new HashMap<>();
5195                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5196            }
5197            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5198            if (sequenceNumber != null) {
5199                changedPackages.remove(sequenceNumber);
5200            }
5201            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5202            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5203        }
5204        mChangedPackagesSequenceNumber++;
5205    }
5206
5207    @Override
5208    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5209        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5210            return null;
5211        }
5212        synchronized (mPackages) {
5213            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5214                return null;
5215            }
5216            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5217            if (changedPackages == null) {
5218                return null;
5219            }
5220            final List<String> packageNames =
5221                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5222            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5223                final String packageName = changedPackages.get(i);
5224                if (packageName != null) {
5225                    packageNames.add(packageName);
5226                }
5227            }
5228            return packageNames.isEmpty()
5229                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5230        }
5231    }
5232
5233    @Override
5234    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5235        // allow instant applications
5236        ArrayList<FeatureInfo> res;
5237        synchronized (mAvailableFeatures) {
5238            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5239            res.addAll(mAvailableFeatures.values());
5240        }
5241        final FeatureInfo fi = new FeatureInfo();
5242        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5243                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5244        res.add(fi);
5245
5246        return new ParceledListSlice<>(res);
5247    }
5248
5249    @Override
5250    public boolean hasSystemFeature(String name, int version) {
5251        // allow instant applications
5252        synchronized (mAvailableFeatures) {
5253            final FeatureInfo feat = mAvailableFeatures.get(name);
5254            if (feat == null) {
5255                return false;
5256            } else {
5257                return feat.version >= version;
5258            }
5259        }
5260    }
5261
5262    @Override
5263    public int checkPermission(String permName, String pkgName, int userId) {
5264        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5265    }
5266
5267    @Override
5268    public int checkUidPermission(String permName, int uid) {
5269        synchronized (mPackages) {
5270            final String[] packageNames = getPackagesForUid(uid);
5271            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5272                    ? mPackages.get(packageNames[0])
5273                    : null;
5274            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5275        }
5276    }
5277
5278    @Override
5279    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5280        if (UserHandle.getCallingUserId() != userId) {
5281            mContext.enforceCallingPermission(
5282                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5283                    "isPermissionRevokedByPolicy for user " + userId);
5284        }
5285
5286        if (checkPermission(permission, packageName, userId)
5287                == PackageManager.PERMISSION_GRANTED) {
5288            return false;
5289        }
5290
5291        final int callingUid = Binder.getCallingUid();
5292        if (getInstantAppPackageName(callingUid) != null) {
5293            if (!isCallerSameApp(packageName, callingUid)) {
5294                return false;
5295            }
5296        } else {
5297            if (isInstantApp(packageName, userId)) {
5298                return false;
5299            }
5300        }
5301
5302        final long identity = Binder.clearCallingIdentity();
5303        try {
5304            final int flags = getPermissionFlags(permission, packageName, userId);
5305            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5306        } finally {
5307            Binder.restoreCallingIdentity(identity);
5308        }
5309    }
5310
5311    @Override
5312    public String getPermissionControllerPackageName() {
5313        synchronized (mPackages) {
5314            return mRequiredInstallerPackage;
5315        }
5316    }
5317
5318    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5319        return mPermissionManager.addDynamicPermission(
5320                info, async, getCallingUid(), new PermissionCallback() {
5321                    @Override
5322                    public void onPermissionChanged() {
5323                        if (!async) {
5324                            mSettings.writeLPr();
5325                        } else {
5326                            scheduleWriteSettingsLocked();
5327                        }
5328                    }
5329                });
5330    }
5331
5332    @Override
5333    public boolean addPermission(PermissionInfo info) {
5334        synchronized (mPackages) {
5335            return addDynamicPermission(info, false);
5336        }
5337    }
5338
5339    @Override
5340    public boolean addPermissionAsync(PermissionInfo info) {
5341        synchronized (mPackages) {
5342            return addDynamicPermission(info, true);
5343        }
5344    }
5345
5346    @Override
5347    public void removePermission(String permName) {
5348        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5349    }
5350
5351    @Override
5352    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5353        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5354                getCallingUid(), userId, mPermissionCallback);
5355    }
5356
5357    @Override
5358    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5359        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5360                getCallingUid(), userId, mPermissionCallback);
5361    }
5362
5363    @Override
5364    public void resetRuntimePermissions() {
5365        mContext.enforceCallingOrSelfPermission(
5366                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5367                "revokeRuntimePermission");
5368
5369        int callingUid = Binder.getCallingUid();
5370        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5371            mContext.enforceCallingOrSelfPermission(
5372                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5373                    "resetRuntimePermissions");
5374        }
5375
5376        synchronized (mPackages) {
5377            mPermissionManager.updateAllPermissions(
5378                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5379                    mPermissionCallback);
5380            for (int userId : UserManagerService.getInstance().getUserIds()) {
5381                final int packageCount = mPackages.size();
5382                for (int i = 0; i < packageCount; i++) {
5383                    PackageParser.Package pkg = mPackages.valueAt(i);
5384                    if (!(pkg.mExtras instanceof PackageSetting)) {
5385                        continue;
5386                    }
5387                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5388                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5389                }
5390            }
5391        }
5392    }
5393
5394    @Override
5395    public int getPermissionFlags(String permName, String packageName, int userId) {
5396        return mPermissionManager.getPermissionFlags(
5397                permName, packageName, getCallingUid(), userId);
5398    }
5399
5400    @Override
5401    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5402            int flagValues, int userId) {
5403        mPermissionManager.updatePermissionFlags(
5404                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5405                mPermissionCallback);
5406    }
5407
5408    /**
5409     * Update the permission flags for all packages and runtime permissions of a user in order
5410     * to allow device or profile owner to remove POLICY_FIXED.
5411     */
5412    @Override
5413    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5414        synchronized (mPackages) {
5415            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5416                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5417                    mPermissionCallback);
5418            if (changed) {
5419                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5420            }
5421        }
5422    }
5423
5424    @Override
5425    public boolean shouldShowRequestPermissionRationale(String permissionName,
5426            String packageName, int userId) {
5427        if (UserHandle.getCallingUserId() != userId) {
5428            mContext.enforceCallingPermission(
5429                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5430                    "canShowRequestPermissionRationale for user " + userId);
5431        }
5432
5433        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5434        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5435            return false;
5436        }
5437
5438        if (checkPermission(permissionName, packageName, userId)
5439                == PackageManager.PERMISSION_GRANTED) {
5440            return false;
5441        }
5442
5443        final int flags;
5444
5445        final long identity = Binder.clearCallingIdentity();
5446        try {
5447            flags = getPermissionFlags(permissionName,
5448                    packageName, userId);
5449        } finally {
5450            Binder.restoreCallingIdentity(identity);
5451        }
5452
5453        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5454                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5455                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5456
5457        if ((flags & fixedFlags) != 0) {
5458            return false;
5459        }
5460
5461        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5462    }
5463
5464    @Override
5465    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5466        mContext.enforceCallingOrSelfPermission(
5467                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5468                "addOnPermissionsChangeListener");
5469
5470        synchronized (mPackages) {
5471            mOnPermissionChangeListeners.addListenerLocked(listener);
5472        }
5473    }
5474
5475    @Override
5476    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5477        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5478            throw new SecurityException("Instant applications don't have access to this method");
5479        }
5480        synchronized (mPackages) {
5481            mOnPermissionChangeListeners.removeListenerLocked(listener);
5482        }
5483    }
5484
5485    @Override
5486    public boolean isProtectedBroadcast(String actionName) {
5487        // allow instant applications
5488        synchronized (mProtectedBroadcasts) {
5489            if (mProtectedBroadcasts.contains(actionName)) {
5490                return true;
5491            } else if (actionName != null) {
5492                // TODO: remove these terrible hacks
5493                if (actionName.startsWith("android.net.netmon.lingerExpired")
5494                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5495                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5496                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5497                    return true;
5498                }
5499            }
5500        }
5501        return false;
5502    }
5503
5504    @Override
5505    public int checkSignatures(String pkg1, String pkg2) {
5506        synchronized (mPackages) {
5507            final PackageParser.Package p1 = mPackages.get(pkg1);
5508            final PackageParser.Package p2 = mPackages.get(pkg2);
5509            if (p1 == null || p1.mExtras == null
5510                    || p2 == null || p2.mExtras == null) {
5511                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5512            }
5513            final int callingUid = Binder.getCallingUid();
5514            final int callingUserId = UserHandle.getUserId(callingUid);
5515            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5516            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5517            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5518                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5519                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5520            }
5521            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5522        }
5523    }
5524
5525    @Override
5526    public int checkUidSignatures(int uid1, int uid2) {
5527        final int callingUid = Binder.getCallingUid();
5528        final int callingUserId = UserHandle.getUserId(callingUid);
5529        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5530        // Map to base uids.
5531        uid1 = UserHandle.getAppId(uid1);
5532        uid2 = UserHandle.getAppId(uid2);
5533        // reader
5534        synchronized (mPackages) {
5535            Signature[] s1;
5536            Signature[] s2;
5537            Object obj = mSettings.getUserIdLPr(uid1);
5538            if (obj != null) {
5539                if (obj instanceof SharedUserSetting) {
5540                    if (isCallerInstantApp) {
5541                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5542                    }
5543                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5544                } else if (obj instanceof PackageSetting) {
5545                    final PackageSetting ps = (PackageSetting) obj;
5546                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5547                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5548                    }
5549                    s1 = ps.signatures.mSigningDetails.signatures;
5550                } else {
5551                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5552                }
5553            } else {
5554                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5555            }
5556            obj = mSettings.getUserIdLPr(uid2);
5557            if (obj != null) {
5558                if (obj instanceof SharedUserSetting) {
5559                    if (isCallerInstantApp) {
5560                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5561                    }
5562                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5563                } else if (obj instanceof PackageSetting) {
5564                    final PackageSetting ps = (PackageSetting) obj;
5565                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5566                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5567                    }
5568                    s2 = ps.signatures.mSigningDetails.signatures;
5569                } else {
5570                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5571                }
5572            } else {
5573                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5574            }
5575            return compareSignatures(s1, s2);
5576        }
5577    }
5578
5579    @Override
5580    public boolean hasSigningCertificate(
5581            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5582
5583        synchronized (mPackages) {
5584            final PackageParser.Package p = mPackages.get(packageName);
5585            if (p == null || p.mExtras == null) {
5586                return false;
5587            }
5588            final int callingUid = Binder.getCallingUid();
5589            final int callingUserId = UserHandle.getUserId(callingUid);
5590            final PackageSetting ps = (PackageSetting) p.mExtras;
5591            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5592                return false;
5593            }
5594            switch (type) {
5595                case CERT_INPUT_RAW_X509:
5596                    return p.mSigningDetails.hasCertificate(certificate);
5597                case CERT_INPUT_SHA256:
5598                    return p.mSigningDetails.hasSha256Certificate(certificate);
5599                default:
5600                    return false;
5601            }
5602        }
5603    }
5604
5605    @Override
5606    public boolean hasUidSigningCertificate(
5607            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5608        final int callingUid = Binder.getCallingUid();
5609        final int callingUserId = UserHandle.getUserId(callingUid);
5610        // Map to base uids.
5611        uid = UserHandle.getAppId(uid);
5612        // reader
5613        synchronized (mPackages) {
5614            final PackageParser.SigningDetails signingDetails;
5615            final Object obj = mSettings.getUserIdLPr(uid);
5616            if (obj != null) {
5617                if (obj instanceof SharedUserSetting) {
5618                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5619                    if (isCallerInstantApp) {
5620                        return false;
5621                    }
5622                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5623                } else if (obj instanceof PackageSetting) {
5624                    final PackageSetting ps = (PackageSetting) obj;
5625                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5626                        return false;
5627                    }
5628                    signingDetails = ps.signatures.mSigningDetails;
5629                } else {
5630                    return false;
5631                }
5632            } else {
5633                return false;
5634            }
5635            switch (type) {
5636                case CERT_INPUT_RAW_X509:
5637                    return signingDetails.hasCertificate(certificate);
5638                case CERT_INPUT_SHA256:
5639                    return signingDetails.hasSha256Certificate(certificate);
5640                default:
5641                    return false;
5642            }
5643        }
5644    }
5645
5646    /**
5647     * This method should typically only be used when granting or revoking
5648     * permissions, since the app may immediately restart after this call.
5649     * <p>
5650     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5651     * guard your work against the app being relaunched.
5652     */
5653    private void killUid(int appId, int userId, String reason) {
5654        final long identity = Binder.clearCallingIdentity();
5655        try {
5656            IActivityManager am = ActivityManager.getService();
5657            if (am != null) {
5658                try {
5659                    am.killUid(appId, userId, reason);
5660                } catch (RemoteException e) {
5661                    /* ignore - same process */
5662                }
5663            }
5664        } finally {
5665            Binder.restoreCallingIdentity(identity);
5666        }
5667    }
5668
5669    /**
5670     * If the database version for this type of package (internal storage or
5671     * external storage) is less than the version where package signatures
5672     * were updated, return true.
5673     */
5674    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5675        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5676        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5677    }
5678
5679    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5680        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5681        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5682    }
5683
5684    @Override
5685    public List<String> getAllPackages() {
5686        final int callingUid = Binder.getCallingUid();
5687        final int callingUserId = UserHandle.getUserId(callingUid);
5688        synchronized (mPackages) {
5689            if (canViewInstantApps(callingUid, callingUserId)) {
5690                return new ArrayList<String>(mPackages.keySet());
5691            }
5692            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5693            final List<String> result = new ArrayList<>();
5694            if (instantAppPkgName != null) {
5695                // caller is an instant application; filter unexposed applications
5696                for (PackageParser.Package pkg : mPackages.values()) {
5697                    if (!pkg.visibleToInstantApps) {
5698                        continue;
5699                    }
5700                    result.add(pkg.packageName);
5701                }
5702            } else {
5703                // caller is a normal application; filter instant applications
5704                for (PackageParser.Package pkg : mPackages.values()) {
5705                    final PackageSetting ps =
5706                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5707                    if (ps != null
5708                            && ps.getInstantApp(callingUserId)
5709                            && !mInstantAppRegistry.isInstantAccessGranted(
5710                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5711                        continue;
5712                    }
5713                    result.add(pkg.packageName);
5714                }
5715            }
5716            return result;
5717        }
5718    }
5719
5720    @Override
5721    public String[] getPackagesForUid(int uid) {
5722        final int callingUid = Binder.getCallingUid();
5723        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5724        final int userId = UserHandle.getUserId(uid);
5725        uid = UserHandle.getAppId(uid);
5726        // reader
5727        synchronized (mPackages) {
5728            Object obj = mSettings.getUserIdLPr(uid);
5729            if (obj instanceof SharedUserSetting) {
5730                if (isCallerInstantApp) {
5731                    return null;
5732                }
5733                final SharedUserSetting sus = (SharedUserSetting) obj;
5734                final int N = sus.packages.size();
5735                String[] res = new String[N];
5736                final Iterator<PackageSetting> it = sus.packages.iterator();
5737                int i = 0;
5738                while (it.hasNext()) {
5739                    PackageSetting ps = it.next();
5740                    if (ps.getInstalled(userId)) {
5741                        res[i++] = ps.name;
5742                    } else {
5743                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5744                    }
5745                }
5746                return res;
5747            } else if (obj instanceof PackageSetting) {
5748                final PackageSetting ps = (PackageSetting) obj;
5749                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5750                    return new String[]{ps.name};
5751                }
5752            }
5753        }
5754        return null;
5755    }
5756
5757    @Override
5758    public String getNameForUid(int uid) {
5759        final int callingUid = Binder.getCallingUid();
5760        if (getInstantAppPackageName(callingUid) != null) {
5761            return null;
5762        }
5763        synchronized (mPackages) {
5764            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5765            if (obj instanceof SharedUserSetting) {
5766                final SharedUserSetting sus = (SharedUserSetting) obj;
5767                return sus.name + ":" + sus.userId;
5768            } else if (obj instanceof PackageSetting) {
5769                final PackageSetting ps = (PackageSetting) obj;
5770                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5771                    return null;
5772                }
5773                return ps.name;
5774            }
5775            return null;
5776        }
5777    }
5778
5779    @Override
5780    public String[] getNamesForUids(int[] uids) {
5781        if (uids == null || uids.length == 0) {
5782            return null;
5783        }
5784        final int callingUid = Binder.getCallingUid();
5785        if (getInstantAppPackageName(callingUid) != null) {
5786            return null;
5787        }
5788        final String[] names = new String[uids.length];
5789        synchronized (mPackages) {
5790            for (int i = uids.length - 1; i >= 0; i--) {
5791                final int uid = uids[i];
5792                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5793                if (obj instanceof SharedUserSetting) {
5794                    final SharedUserSetting sus = (SharedUserSetting) obj;
5795                    names[i] = "shared:" + sus.name;
5796                } else if (obj instanceof PackageSetting) {
5797                    final PackageSetting ps = (PackageSetting) obj;
5798                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5799                        names[i] = null;
5800                    } else {
5801                        names[i] = ps.name;
5802                    }
5803                } else {
5804                    names[i] = null;
5805                }
5806            }
5807        }
5808        return names;
5809    }
5810
5811    @Override
5812    public int getUidForSharedUser(String sharedUserName) {
5813        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5814            return -1;
5815        }
5816        if (sharedUserName == null) {
5817            return -1;
5818        }
5819        // reader
5820        synchronized (mPackages) {
5821            SharedUserSetting suid;
5822            try {
5823                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5824                if (suid != null) {
5825                    return suid.userId;
5826                }
5827            } catch (PackageManagerException ignore) {
5828                // can't happen, but, still need to catch it
5829            }
5830            return -1;
5831        }
5832    }
5833
5834    @Override
5835    public int getFlagsForUid(int uid) {
5836        final int callingUid = Binder.getCallingUid();
5837        if (getInstantAppPackageName(callingUid) != null) {
5838            return 0;
5839        }
5840        synchronized (mPackages) {
5841            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5842            if (obj instanceof SharedUserSetting) {
5843                final SharedUserSetting sus = (SharedUserSetting) obj;
5844                return sus.pkgFlags;
5845            } else if (obj instanceof PackageSetting) {
5846                final PackageSetting ps = (PackageSetting) obj;
5847                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5848                    return 0;
5849                }
5850                return ps.pkgFlags;
5851            }
5852        }
5853        return 0;
5854    }
5855
5856    @Override
5857    public int getPrivateFlagsForUid(int uid) {
5858        final int callingUid = Binder.getCallingUid();
5859        if (getInstantAppPackageName(callingUid) != null) {
5860            return 0;
5861        }
5862        synchronized (mPackages) {
5863            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5864            if (obj instanceof SharedUserSetting) {
5865                final SharedUserSetting sus = (SharedUserSetting) obj;
5866                return sus.pkgPrivateFlags;
5867            } else if (obj instanceof PackageSetting) {
5868                final PackageSetting ps = (PackageSetting) obj;
5869                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5870                    return 0;
5871                }
5872                return ps.pkgPrivateFlags;
5873            }
5874        }
5875        return 0;
5876    }
5877
5878    @Override
5879    public boolean isUidPrivileged(int uid) {
5880        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5881            return false;
5882        }
5883        uid = UserHandle.getAppId(uid);
5884        // reader
5885        synchronized (mPackages) {
5886            Object obj = mSettings.getUserIdLPr(uid);
5887            if (obj instanceof SharedUserSetting) {
5888                final SharedUserSetting sus = (SharedUserSetting) obj;
5889                final Iterator<PackageSetting> it = sus.packages.iterator();
5890                while (it.hasNext()) {
5891                    if (it.next().isPrivileged()) {
5892                        return true;
5893                    }
5894                }
5895            } else if (obj instanceof PackageSetting) {
5896                final PackageSetting ps = (PackageSetting) obj;
5897                return ps.isPrivileged();
5898            }
5899        }
5900        return false;
5901    }
5902
5903    @Override
5904    public String[] getAppOpPermissionPackages(String permName) {
5905        return mPermissionManager.getAppOpPermissionPackages(permName);
5906    }
5907
5908    @Override
5909    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5910            int flags, int userId) {
5911        return resolveIntentInternal(
5912                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5913    }
5914
5915    /**
5916     * Normally instant apps can only be resolved when they're visible to the caller.
5917     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5918     * since we need to allow the system to start any installed application.
5919     */
5920    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5921            int flags, int userId, boolean resolveForStart) {
5922        try {
5923            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5924
5925            if (!sUserManager.exists(userId)) return null;
5926            final int callingUid = Binder.getCallingUid();
5927            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5928            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5929                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5930
5931            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5932            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5933                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5934            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5935
5936            final ResolveInfo bestChoice =
5937                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5938            return bestChoice;
5939        } finally {
5940            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5941        }
5942    }
5943
5944    @Override
5945    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5946        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5947            throw new SecurityException(
5948                    "findPersistentPreferredActivity can only be run by the system");
5949        }
5950        if (!sUserManager.exists(userId)) {
5951            return null;
5952        }
5953        final int callingUid = Binder.getCallingUid();
5954        intent = updateIntentForResolve(intent);
5955        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5956        final int flags = updateFlagsForResolve(
5957                0, userId, intent, callingUid, false /*includeInstantApps*/);
5958        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5959                userId);
5960        synchronized (mPackages) {
5961            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5962                    userId);
5963        }
5964    }
5965
5966    @Override
5967    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5968            IntentFilter filter, int match, ComponentName activity) {
5969        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5970            return;
5971        }
5972        final int userId = UserHandle.getCallingUserId();
5973        if (DEBUG_PREFERRED) {
5974            Log.v(TAG, "setLastChosenActivity intent=" + intent
5975                + " resolvedType=" + resolvedType
5976                + " flags=" + flags
5977                + " filter=" + filter
5978                + " match=" + match
5979                + " activity=" + activity);
5980            filter.dump(new PrintStreamPrinter(System.out), "    ");
5981        }
5982        intent.setComponent(null);
5983        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5984                userId);
5985        // Find any earlier preferred or last chosen entries and nuke them
5986        findPreferredActivity(intent, resolvedType,
5987                flags, query, 0, false, true, false, userId);
5988        // Add the new activity as the last chosen for this filter
5989        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5990                "Setting last chosen");
5991    }
5992
5993    @Override
5994    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5995        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5996            return null;
5997        }
5998        final int userId = UserHandle.getCallingUserId();
5999        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6000        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6001                userId);
6002        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6003                false, false, false, userId);
6004    }
6005
6006    /**
6007     * Returns whether or not instant apps have been disabled remotely.
6008     */
6009    private boolean areWebInstantAppsDisabled() {
6010        return mWebInstantAppsDisabled;
6011    }
6012
6013    private boolean isInstantAppResolutionAllowed(
6014            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6015            boolean skipPackageCheck) {
6016        if (mInstantAppResolverConnection == null) {
6017            return false;
6018        }
6019        if (mInstantAppInstallerActivity == null) {
6020            return false;
6021        }
6022        if (intent.getComponent() != null) {
6023            return false;
6024        }
6025        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6026            return false;
6027        }
6028        if (!skipPackageCheck && intent.getPackage() != null) {
6029            return false;
6030        }
6031        if (!intent.isWebIntent()) {
6032            // for non web intents, we should not resolve externally if an app already exists to
6033            // handle it or if the caller didn't explicitly request it.
6034            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6035                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6036                return false;
6037            }
6038        } else {
6039            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6040                return false;
6041            } else if (areWebInstantAppsDisabled()) {
6042                return false;
6043            }
6044        }
6045        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6046        // Or if there's already an ephemeral app installed that handles the action
6047        synchronized (mPackages) {
6048            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6049            for (int n = 0; n < count; n++) {
6050                final ResolveInfo info = resolvedActivities.get(n);
6051                final String packageName = info.activityInfo.packageName;
6052                final PackageSetting ps = mSettings.mPackages.get(packageName);
6053                if (ps != null) {
6054                    // only check domain verification status if the app is not a browser
6055                    if (!info.handleAllWebDataURI) {
6056                        // Try to get the status from User settings first
6057                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6058                        final int status = (int) (packedStatus >> 32);
6059                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6060                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6061                            if (DEBUG_INSTANT) {
6062                                Slog.v(TAG, "DENY instant app;"
6063                                    + " pkg: " + packageName + ", status: " + status);
6064                            }
6065                            return false;
6066                        }
6067                    }
6068                    if (ps.getInstantApp(userId)) {
6069                        if (DEBUG_INSTANT) {
6070                            Slog.v(TAG, "DENY instant app installed;"
6071                                    + " pkg: " + packageName);
6072                        }
6073                        return false;
6074                    }
6075                }
6076            }
6077        }
6078        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6079        return true;
6080    }
6081
6082    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6083            Intent origIntent, String resolvedType, String callingPackage,
6084            Bundle verificationBundle, int userId) {
6085        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6086                new InstantAppRequest(responseObj, origIntent, resolvedType,
6087                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6088        mHandler.sendMessage(msg);
6089    }
6090
6091    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6092            int flags, List<ResolveInfo> query, int userId) {
6093        if (query != null) {
6094            final int N = query.size();
6095            if (N == 1) {
6096                return query.get(0);
6097            } else if (N > 1) {
6098                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6099                // If there is more than one activity with the same priority,
6100                // then let the user decide between them.
6101                ResolveInfo r0 = query.get(0);
6102                ResolveInfo r1 = query.get(1);
6103                if (DEBUG_INTENT_MATCHING || debug) {
6104                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6105                            + r1.activityInfo.name + "=" + r1.priority);
6106                }
6107                // If the first activity has a higher priority, or a different
6108                // default, then it is always desirable to pick it.
6109                if (r0.priority != r1.priority
6110                        || r0.preferredOrder != r1.preferredOrder
6111                        || r0.isDefault != r1.isDefault) {
6112                    return query.get(0);
6113                }
6114                // If we have saved a preference for a preferred activity for
6115                // this Intent, use that.
6116                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6117                        flags, query, r0.priority, true, false, debug, userId);
6118                if (ri != null) {
6119                    return ri;
6120                }
6121                // If we have an ephemeral app, use it
6122                for (int i = 0; i < N; i++) {
6123                    ri = query.get(i);
6124                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6125                        final String packageName = ri.activityInfo.packageName;
6126                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6127                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6128                        final int status = (int)(packedStatus >> 32);
6129                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6130                            return ri;
6131                        }
6132                    }
6133                }
6134                ri = new ResolveInfo(mResolveInfo);
6135                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6136                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6137                // If all of the options come from the same package, show the application's
6138                // label and icon instead of the generic resolver's.
6139                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6140                // and then throw away the ResolveInfo itself, meaning that the caller loses
6141                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6142                // a fallback for this case; we only set the target package's resources on
6143                // the ResolveInfo, not the ActivityInfo.
6144                final String intentPackage = intent.getPackage();
6145                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6146                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6147                    ri.resolvePackageName = intentPackage;
6148                    if (userNeedsBadging(userId)) {
6149                        ri.noResourceId = true;
6150                    } else {
6151                        ri.icon = appi.icon;
6152                    }
6153                    ri.iconResourceId = appi.icon;
6154                    ri.labelRes = appi.labelRes;
6155                }
6156                ri.activityInfo.applicationInfo = new ApplicationInfo(
6157                        ri.activityInfo.applicationInfo);
6158                if (userId != 0) {
6159                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6160                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6161                }
6162                // Make sure that the resolver is displayable in car mode
6163                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6164                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6165                return ri;
6166            }
6167        }
6168        return null;
6169    }
6170
6171    /**
6172     * Return true if the given list is not empty and all of its contents have
6173     * an activityInfo with the given package name.
6174     */
6175    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6176        if (ArrayUtils.isEmpty(list)) {
6177            return false;
6178        }
6179        for (int i = 0, N = list.size(); i < N; i++) {
6180            final ResolveInfo ri = list.get(i);
6181            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6182            if (ai == null || !packageName.equals(ai.packageName)) {
6183                return false;
6184            }
6185        }
6186        return true;
6187    }
6188
6189    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6190            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6191        final int N = query.size();
6192        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6193                .get(userId);
6194        // Get the list of persistent preferred activities that handle the intent
6195        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6196        List<PersistentPreferredActivity> pprefs = ppir != null
6197                ? ppir.queryIntent(intent, resolvedType,
6198                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6199                        userId)
6200                : null;
6201        if (pprefs != null && pprefs.size() > 0) {
6202            final int M = pprefs.size();
6203            for (int i=0; i<M; i++) {
6204                final PersistentPreferredActivity ppa = pprefs.get(i);
6205                if (DEBUG_PREFERRED || debug) {
6206                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6207                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6208                            + "\n  component=" + ppa.mComponent);
6209                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6210                }
6211                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6212                        flags | MATCH_DISABLED_COMPONENTS, userId);
6213                if (DEBUG_PREFERRED || debug) {
6214                    Slog.v(TAG, "Found persistent preferred activity:");
6215                    if (ai != null) {
6216                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6217                    } else {
6218                        Slog.v(TAG, "  null");
6219                    }
6220                }
6221                if (ai == null) {
6222                    // This previously registered persistent preferred activity
6223                    // component is no longer known. Ignore it and do NOT remove it.
6224                    continue;
6225                }
6226                for (int j=0; j<N; j++) {
6227                    final ResolveInfo ri = query.get(j);
6228                    if (!ri.activityInfo.applicationInfo.packageName
6229                            .equals(ai.applicationInfo.packageName)) {
6230                        continue;
6231                    }
6232                    if (!ri.activityInfo.name.equals(ai.name)) {
6233                        continue;
6234                    }
6235                    //  Found a persistent preference that can handle the intent.
6236                    if (DEBUG_PREFERRED || debug) {
6237                        Slog.v(TAG, "Returning persistent preferred activity: " +
6238                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6239                    }
6240                    return ri;
6241                }
6242            }
6243        }
6244        return null;
6245    }
6246
6247    // TODO: handle preferred activities missing while user has amnesia
6248    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6249            List<ResolveInfo> query, int priority, boolean always,
6250            boolean removeMatches, boolean debug, int userId) {
6251        if (!sUserManager.exists(userId)) return null;
6252        final int callingUid = Binder.getCallingUid();
6253        flags = updateFlagsForResolve(
6254                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6255        intent = updateIntentForResolve(intent);
6256        // writer
6257        synchronized (mPackages) {
6258            // Try to find a matching persistent preferred activity.
6259            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6260                    debug, userId);
6261
6262            // If a persistent preferred activity matched, use it.
6263            if (pri != null) {
6264                return pri;
6265            }
6266
6267            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6268            // Get the list of preferred activities that handle the intent
6269            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6270            List<PreferredActivity> prefs = pir != null
6271                    ? pir.queryIntent(intent, resolvedType,
6272                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6273                            userId)
6274                    : null;
6275            if (prefs != null && prefs.size() > 0) {
6276                boolean changed = false;
6277                try {
6278                    // First figure out how good the original match set is.
6279                    // We will only allow preferred activities that came
6280                    // from the same match quality.
6281                    int match = 0;
6282
6283                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6284
6285                    final int N = query.size();
6286                    for (int j=0; j<N; j++) {
6287                        final ResolveInfo ri = query.get(j);
6288                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6289                                + ": 0x" + Integer.toHexString(match));
6290                        if (ri.match > match) {
6291                            match = ri.match;
6292                        }
6293                    }
6294
6295                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6296                            + Integer.toHexString(match));
6297
6298                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6299                    final int M = prefs.size();
6300                    for (int i=0; i<M; i++) {
6301                        final PreferredActivity pa = prefs.get(i);
6302                        if (DEBUG_PREFERRED || debug) {
6303                            Slog.v(TAG, "Checking PreferredActivity ds="
6304                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6305                                    + "\n  component=" + pa.mPref.mComponent);
6306                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6307                        }
6308                        if (pa.mPref.mMatch != match) {
6309                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6310                                    + Integer.toHexString(pa.mPref.mMatch));
6311                            continue;
6312                        }
6313                        // If it's not an "always" type preferred activity and that's what we're
6314                        // looking for, skip it.
6315                        if (always && !pa.mPref.mAlways) {
6316                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6317                            continue;
6318                        }
6319                        final ActivityInfo ai = getActivityInfo(
6320                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6321                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6322                                userId);
6323                        if (DEBUG_PREFERRED || debug) {
6324                            Slog.v(TAG, "Found preferred activity:");
6325                            if (ai != null) {
6326                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6327                            } else {
6328                                Slog.v(TAG, "  null");
6329                            }
6330                        }
6331                        if (ai == null) {
6332                            // This previously registered preferred activity
6333                            // component is no longer known.  Most likely an update
6334                            // to the app was installed and in the new version this
6335                            // component no longer exists.  Clean it up by removing
6336                            // it from the preferred activities list, and skip it.
6337                            Slog.w(TAG, "Removing dangling preferred activity: "
6338                                    + pa.mPref.mComponent);
6339                            pir.removeFilter(pa);
6340                            changed = true;
6341                            continue;
6342                        }
6343                        for (int j=0; j<N; j++) {
6344                            final ResolveInfo ri = query.get(j);
6345                            if (!ri.activityInfo.applicationInfo.packageName
6346                                    .equals(ai.applicationInfo.packageName)) {
6347                                continue;
6348                            }
6349                            if (!ri.activityInfo.name.equals(ai.name)) {
6350                                continue;
6351                            }
6352
6353                            if (removeMatches) {
6354                                pir.removeFilter(pa);
6355                                changed = true;
6356                                if (DEBUG_PREFERRED) {
6357                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6358                                }
6359                                break;
6360                            }
6361
6362                            // Okay we found a previously set preferred or last chosen app.
6363                            // If the result set is different from when this
6364                            // was created, and is not a subset of the preferred set, we need to
6365                            // clear it and re-ask the user their preference, if we're looking for
6366                            // an "always" type entry.
6367                            if (always && !pa.mPref.sameSet(query)) {
6368                                if (pa.mPref.isSuperset(query)) {
6369                                    // some components of the set are no longer present in
6370                                    // the query, but the preferred activity can still be reused
6371                                    if (DEBUG_PREFERRED) {
6372                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6373                                                + " still valid as only non-preferred components"
6374                                                + " were removed for " + intent + " type "
6375                                                + resolvedType);
6376                                    }
6377                                    // remove obsolete components and re-add the up-to-date filter
6378                                    PreferredActivity freshPa = new PreferredActivity(pa,
6379                                            pa.mPref.mMatch,
6380                                            pa.mPref.discardObsoleteComponents(query),
6381                                            pa.mPref.mComponent,
6382                                            pa.mPref.mAlways);
6383                                    pir.removeFilter(pa);
6384                                    pir.addFilter(freshPa);
6385                                    changed = true;
6386                                } else {
6387                                    Slog.i(TAG,
6388                                            "Result set changed, dropping preferred activity for "
6389                                                    + intent + " type " + resolvedType);
6390                                    if (DEBUG_PREFERRED) {
6391                                        Slog.v(TAG, "Removing preferred activity since set changed "
6392                                                + pa.mPref.mComponent);
6393                                    }
6394                                    pir.removeFilter(pa);
6395                                    // Re-add the filter as a "last chosen" entry (!always)
6396                                    PreferredActivity lastChosen = new PreferredActivity(
6397                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6398                                    pir.addFilter(lastChosen);
6399                                    changed = true;
6400                                    return null;
6401                                }
6402                            }
6403
6404                            // Yay! Either the set matched or we're looking for the last chosen
6405                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6406                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6407                            return ri;
6408                        }
6409                    }
6410                } finally {
6411                    if (changed) {
6412                        if (DEBUG_PREFERRED) {
6413                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6414                        }
6415                        scheduleWritePackageRestrictionsLocked(userId);
6416                    }
6417                }
6418            }
6419        }
6420        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6421        return null;
6422    }
6423
6424    /*
6425     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6426     */
6427    @Override
6428    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6429            int targetUserId) {
6430        mContext.enforceCallingOrSelfPermission(
6431                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6432        List<CrossProfileIntentFilter> matches =
6433                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6434        if (matches != null) {
6435            int size = matches.size();
6436            for (int i = 0; i < size; i++) {
6437                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6438            }
6439        }
6440        if (intent.hasWebURI()) {
6441            // cross-profile app linking works only towards the parent.
6442            final int callingUid = Binder.getCallingUid();
6443            final UserInfo parent = getProfileParent(sourceUserId);
6444            synchronized(mPackages) {
6445                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6446                        false /*includeInstantApps*/);
6447                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6448                        intent, resolvedType, flags, sourceUserId, parent.id);
6449                return xpDomainInfo != null;
6450            }
6451        }
6452        return false;
6453    }
6454
6455    private UserInfo getProfileParent(int userId) {
6456        final long identity = Binder.clearCallingIdentity();
6457        try {
6458            return sUserManager.getProfileParent(userId);
6459        } finally {
6460            Binder.restoreCallingIdentity(identity);
6461        }
6462    }
6463
6464    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6465            String resolvedType, int userId) {
6466        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6467        if (resolver != null) {
6468            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6469        }
6470        return null;
6471    }
6472
6473    @Override
6474    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6475            String resolvedType, int flags, int userId) {
6476        try {
6477            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6478
6479            return new ParceledListSlice<>(
6480                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6481        } finally {
6482            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6483        }
6484    }
6485
6486    /**
6487     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6488     * instant, returns {@code null}.
6489     */
6490    private String getInstantAppPackageName(int callingUid) {
6491        synchronized (mPackages) {
6492            // If the caller is an isolated app use the owner's uid for the lookup.
6493            if (Process.isIsolated(callingUid)) {
6494                callingUid = mIsolatedOwners.get(callingUid);
6495            }
6496            final int appId = UserHandle.getAppId(callingUid);
6497            final Object obj = mSettings.getUserIdLPr(appId);
6498            if (obj instanceof PackageSetting) {
6499                final PackageSetting ps = (PackageSetting) obj;
6500                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6501                return isInstantApp ? ps.pkg.packageName : null;
6502            }
6503        }
6504        return null;
6505    }
6506
6507    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6508            String resolvedType, int flags, int userId) {
6509        return queryIntentActivitiesInternal(
6510                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6511                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6512    }
6513
6514    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6515            String resolvedType, int flags, int filterCallingUid, int userId,
6516            boolean resolveForStart, boolean allowDynamicSplits) {
6517        if (!sUserManager.exists(userId)) return Collections.emptyList();
6518        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6519        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6520                false /* requireFullPermission */, false /* checkShell */,
6521                "query intent activities");
6522        final String pkgName = intent.getPackage();
6523        ComponentName comp = intent.getComponent();
6524        if (comp == null) {
6525            if (intent.getSelector() != null) {
6526                intent = intent.getSelector();
6527                comp = intent.getComponent();
6528            }
6529        }
6530
6531        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6532                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6533        if (comp != null) {
6534            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6535            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6536            if (ai != null) {
6537                // When specifying an explicit component, we prevent the activity from being
6538                // used when either 1) the calling package is normal and the activity is within
6539                // an ephemeral application or 2) the calling package is ephemeral and the
6540                // activity is not visible to ephemeral applications.
6541                final boolean matchInstantApp =
6542                        (flags & PackageManager.MATCH_INSTANT) != 0;
6543                final boolean matchVisibleToInstantAppOnly =
6544                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6545                final boolean matchExplicitlyVisibleOnly =
6546                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6547                final boolean isCallerInstantApp =
6548                        instantAppPkgName != null;
6549                final boolean isTargetSameInstantApp =
6550                        comp.getPackageName().equals(instantAppPkgName);
6551                final boolean isTargetInstantApp =
6552                        (ai.applicationInfo.privateFlags
6553                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6554                final boolean isTargetVisibleToInstantApp =
6555                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6556                final boolean isTargetExplicitlyVisibleToInstantApp =
6557                        isTargetVisibleToInstantApp
6558                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6559                final boolean isTargetHiddenFromInstantApp =
6560                        !isTargetVisibleToInstantApp
6561                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6562                final boolean blockResolution =
6563                        !isTargetSameInstantApp
6564                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6565                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6566                                        && isTargetHiddenFromInstantApp));
6567                if (!blockResolution) {
6568                    final ResolveInfo ri = new ResolveInfo();
6569                    ri.activityInfo = ai;
6570                    list.add(ri);
6571                }
6572            }
6573            return applyPostResolutionFilter(
6574                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6575        }
6576
6577        // reader
6578        boolean sortResult = false;
6579        boolean addInstant = false;
6580        List<ResolveInfo> result;
6581        synchronized (mPackages) {
6582            if (pkgName == null) {
6583                List<CrossProfileIntentFilter> matchingFilters =
6584                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6585                // Check for results that need to skip the current profile.
6586                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6587                        resolvedType, flags, userId);
6588                if (xpResolveInfo != null) {
6589                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6590                    xpResult.add(xpResolveInfo);
6591                    return applyPostResolutionFilter(
6592                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6593                            allowDynamicSplits, filterCallingUid, userId, intent);
6594                }
6595
6596                // Check for results in the current profile.
6597                result = filterIfNotSystemUser(mActivities.queryIntent(
6598                        intent, resolvedType, flags, userId), userId);
6599                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6600                        false /*skipPackageCheck*/);
6601                // Check for cross profile results.
6602                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6603                xpResolveInfo = queryCrossProfileIntents(
6604                        matchingFilters, intent, resolvedType, flags, userId,
6605                        hasNonNegativePriorityResult);
6606                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6607                    boolean isVisibleToUser = filterIfNotSystemUser(
6608                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6609                    if (isVisibleToUser) {
6610                        result.add(xpResolveInfo);
6611                        sortResult = true;
6612                    }
6613                }
6614                if (intent.hasWebURI()) {
6615                    CrossProfileDomainInfo xpDomainInfo = null;
6616                    final UserInfo parent = getProfileParent(userId);
6617                    if (parent != null) {
6618                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6619                                flags, userId, parent.id);
6620                    }
6621                    if (xpDomainInfo != null) {
6622                        if (xpResolveInfo != null) {
6623                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6624                            // in the result.
6625                            result.remove(xpResolveInfo);
6626                        }
6627                        if (result.size() == 0 && !addInstant) {
6628                            // No result in current profile, but found candidate in parent user.
6629                            // And we are not going to add emphemeral app, so we can return the
6630                            // result straight away.
6631                            result.add(xpDomainInfo.resolveInfo);
6632                            return applyPostResolutionFilter(result, instantAppPkgName,
6633                                    allowDynamicSplits, filterCallingUid, userId, intent);
6634                        }
6635                    } else if (result.size() <= 1 && !addInstant) {
6636                        // No result in parent user and <= 1 result in current profile, and we
6637                        // are not going to add emphemeral app, so we can return the result without
6638                        // further processing.
6639                        return applyPostResolutionFilter(result, instantAppPkgName,
6640                                allowDynamicSplits, filterCallingUid, userId, intent);
6641                    }
6642                    // We have more than one candidate (combining results from current and parent
6643                    // profile), so we need filtering and sorting.
6644                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6645                            intent, flags, result, xpDomainInfo, userId);
6646                    sortResult = true;
6647                }
6648            } else {
6649                final PackageParser.Package pkg = mPackages.get(pkgName);
6650                result = null;
6651                if (pkg != null) {
6652                    result = filterIfNotSystemUser(
6653                            mActivities.queryIntentForPackage(
6654                                    intent, resolvedType, flags, pkg.activities, userId),
6655                            userId);
6656                }
6657                if (result == null || result.size() == 0) {
6658                    // the caller wants to resolve for a particular package; however, there
6659                    // were no installed results, so, try to find an ephemeral result
6660                    addInstant = isInstantAppResolutionAllowed(
6661                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6662                    if (result == null) {
6663                        result = new ArrayList<>();
6664                    }
6665                }
6666            }
6667        }
6668        if (addInstant) {
6669            result = maybeAddInstantAppInstaller(
6670                    result, intent, resolvedType, flags, userId, resolveForStart);
6671        }
6672        if (sortResult) {
6673            Collections.sort(result, mResolvePrioritySorter);
6674        }
6675        return applyPostResolutionFilter(
6676                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6677    }
6678
6679    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6680            String resolvedType, int flags, int userId, boolean resolveForStart) {
6681        // first, check to see if we've got an instant app already installed
6682        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6683        ResolveInfo localInstantApp = null;
6684        boolean blockResolution = false;
6685        if (!alreadyResolvedLocally) {
6686            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6687                    flags
6688                        | PackageManager.GET_RESOLVED_FILTER
6689                        | PackageManager.MATCH_INSTANT
6690                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6691                    userId);
6692            for (int i = instantApps.size() - 1; i >= 0; --i) {
6693                final ResolveInfo info = instantApps.get(i);
6694                final String packageName = info.activityInfo.packageName;
6695                final PackageSetting ps = mSettings.mPackages.get(packageName);
6696                if (ps.getInstantApp(userId)) {
6697                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6698                    final int status = (int)(packedStatus >> 32);
6699                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6700                        // there's a local instant application installed, but, the user has
6701                        // chosen to never use it; skip resolution and don't acknowledge
6702                        // an instant application is even available
6703                        if (DEBUG_INSTANT) {
6704                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6705                        }
6706                        blockResolution = true;
6707                        break;
6708                    } else {
6709                        // we have a locally installed instant application; skip resolution
6710                        // but acknowledge there's an instant application available
6711                        if (DEBUG_INSTANT) {
6712                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6713                        }
6714                        localInstantApp = info;
6715                        break;
6716                    }
6717                }
6718            }
6719        }
6720        // no app installed, let's see if one's available
6721        AuxiliaryResolveInfo auxiliaryResponse = null;
6722        if (!blockResolution) {
6723            if (localInstantApp == null) {
6724                // we don't have an instant app locally, resolve externally
6725                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6726                final InstantAppRequest requestObject = new InstantAppRequest(
6727                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6728                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6729                        resolveForStart);
6730                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6731                        mInstantAppResolverConnection, requestObject);
6732                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6733            } else {
6734                // we have an instant application locally, but, we can't admit that since
6735                // callers shouldn't be able to determine prior browsing. create a dummy
6736                // auxiliary response so the downstream code behaves as if there's an
6737                // instant application available externally. when it comes time to start
6738                // the instant application, we'll do the right thing.
6739                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6740                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6741                                        ai.packageName, ai.versionCode, null /* splitName */);
6742            }
6743        }
6744        if (intent.isWebIntent() && auxiliaryResponse == null) {
6745            return result;
6746        }
6747        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6748        if (ps == null
6749                || ps.getUserState().get(userId) == null
6750                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6751            return result;
6752        }
6753        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6754        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6755                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6756        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6757                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6758        // add a non-generic filter
6759        ephemeralInstaller.filter = new IntentFilter();
6760        if (intent.getAction() != null) {
6761            ephemeralInstaller.filter.addAction(intent.getAction());
6762        }
6763        if (intent.getData() != null && intent.getData().getPath() != null) {
6764            ephemeralInstaller.filter.addDataPath(
6765                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6766        }
6767        ephemeralInstaller.isInstantAppAvailable = true;
6768        // make sure this resolver is the default
6769        ephemeralInstaller.isDefault = true;
6770        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6771        if (DEBUG_INSTANT) {
6772            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6773        }
6774
6775        result.add(ephemeralInstaller);
6776        return result;
6777    }
6778
6779    private static class CrossProfileDomainInfo {
6780        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6781        ResolveInfo resolveInfo;
6782        /* Best domain verification status of the activities found in the other profile */
6783        int bestDomainVerificationStatus;
6784    }
6785
6786    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6787            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6788        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6789                sourceUserId)) {
6790            return null;
6791        }
6792        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6793                resolvedType, flags, parentUserId);
6794
6795        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6796            return null;
6797        }
6798        CrossProfileDomainInfo result = null;
6799        int size = resultTargetUser.size();
6800        for (int i = 0; i < size; i++) {
6801            ResolveInfo riTargetUser = resultTargetUser.get(i);
6802            // Intent filter verification is only for filters that specify a host. So don't return
6803            // those that handle all web uris.
6804            if (riTargetUser.handleAllWebDataURI) {
6805                continue;
6806            }
6807            String packageName = riTargetUser.activityInfo.packageName;
6808            PackageSetting ps = mSettings.mPackages.get(packageName);
6809            if (ps == null) {
6810                continue;
6811            }
6812            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6813            int status = (int)(verificationState >> 32);
6814            if (result == null) {
6815                result = new CrossProfileDomainInfo();
6816                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6817                        sourceUserId, parentUserId);
6818                result.bestDomainVerificationStatus = status;
6819            } else {
6820                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6821                        result.bestDomainVerificationStatus);
6822            }
6823        }
6824        // Don't consider matches with status NEVER across profiles.
6825        if (result != null && result.bestDomainVerificationStatus
6826                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6827            return null;
6828        }
6829        return result;
6830    }
6831
6832    /**
6833     * Verification statuses are ordered from the worse to the best, except for
6834     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6835     */
6836    private int bestDomainVerificationStatus(int status1, int status2) {
6837        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6838            return status2;
6839        }
6840        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6841            return status1;
6842        }
6843        return (int) MathUtils.max(status1, status2);
6844    }
6845
6846    private boolean isUserEnabled(int userId) {
6847        long callingId = Binder.clearCallingIdentity();
6848        try {
6849            UserInfo userInfo = sUserManager.getUserInfo(userId);
6850            return userInfo != null && userInfo.isEnabled();
6851        } finally {
6852            Binder.restoreCallingIdentity(callingId);
6853        }
6854    }
6855
6856    /**
6857     * Filter out activities with systemUserOnly flag set, when current user is not System.
6858     *
6859     * @return filtered list
6860     */
6861    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6862        if (userId == UserHandle.USER_SYSTEM) {
6863            return resolveInfos;
6864        }
6865        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6866            ResolveInfo info = resolveInfos.get(i);
6867            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6868                resolveInfos.remove(i);
6869            }
6870        }
6871        return resolveInfos;
6872    }
6873
6874    /**
6875     * Filters out ephemeral activities.
6876     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6877     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6878     *
6879     * @param resolveInfos The pre-filtered list of resolved activities
6880     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6881     *          is performed.
6882     * @param intent
6883     * @return A filtered list of resolved activities.
6884     */
6885    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6886            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6887            Intent intent) {
6888        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6889        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6890            final ResolveInfo info = resolveInfos.get(i);
6891            // remove locally resolved instant app web results when disabled
6892            if (info.isInstantAppAvailable && blockInstant) {
6893                resolveInfos.remove(i);
6894                continue;
6895            }
6896            // allow activities that are defined in the provided package
6897            if (allowDynamicSplits
6898                    && info.activityInfo != null
6899                    && info.activityInfo.splitName != null
6900                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6901                            info.activityInfo.splitName)) {
6902                if (mInstantAppInstallerActivity == null) {
6903                    if (DEBUG_INSTALL) {
6904                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6905                    }
6906                    resolveInfos.remove(i);
6907                    continue;
6908                }
6909                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6910                    resolveInfos.remove(i);
6911                    continue;
6912                }
6913                // requested activity is defined in a split that hasn't been installed yet.
6914                // add the installer to the resolve list
6915                if (DEBUG_INSTALL) {
6916                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6917                }
6918                final ResolveInfo installerInfo = new ResolveInfo(
6919                        mInstantAppInstallerInfo);
6920                final ComponentName installFailureActivity = findInstallFailureActivity(
6921                        info.activityInfo.packageName,  filterCallingUid, userId);
6922                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6923                        installFailureActivity,
6924                        info.activityInfo.packageName,
6925                        info.activityInfo.applicationInfo.versionCode,
6926                        info.activityInfo.splitName);
6927                // add a non-generic filter
6928                installerInfo.filter = new IntentFilter();
6929
6930                // This resolve info may appear in the chooser UI, so let us make it
6931                // look as the one it replaces as far as the user is concerned which
6932                // requires loading the correct label and icon for the resolve info.
6933                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6934                installerInfo.labelRes = info.resolveLabelResId();
6935                installerInfo.icon = info.resolveIconResId();
6936                installerInfo.isInstantAppAvailable = true;
6937                resolveInfos.set(i, installerInfo);
6938                continue;
6939            }
6940            // caller is a full app, don't need to apply any other filtering
6941            if (ephemeralPkgName == null) {
6942                continue;
6943            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6944                // caller is same app; don't need to apply any other filtering
6945                continue;
6946            }
6947            // allow activities that have been explicitly exposed to ephemeral apps
6948            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6949            if (!isEphemeralApp
6950                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6951                continue;
6952            }
6953            resolveInfos.remove(i);
6954        }
6955        return resolveInfos;
6956    }
6957
6958    /**
6959     * Returns the activity component that can handle install failures.
6960     * <p>By default, the instant application installer handles failures. However, an
6961     * application may want to handle failures on its own. Applications do this by
6962     * creating an activity with an intent filter that handles the action
6963     * {@link Intent#ACTION_INSTALL_FAILURE}.
6964     */
6965    private @Nullable ComponentName findInstallFailureActivity(
6966            String packageName, int filterCallingUid, int userId) {
6967        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6968        failureActivityIntent.setPackage(packageName);
6969        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6970        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6971                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6972                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6973        final int NR = result.size();
6974        if (NR > 0) {
6975            for (int i = 0; i < NR; i++) {
6976                final ResolveInfo info = result.get(i);
6977                if (info.activityInfo.splitName != null) {
6978                    continue;
6979                }
6980                return new ComponentName(packageName, info.activityInfo.name);
6981            }
6982        }
6983        return null;
6984    }
6985
6986    /**
6987     * @param resolveInfos list of resolve infos in descending priority order
6988     * @return if the list contains a resolve info with non-negative priority
6989     */
6990    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6991        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6992    }
6993
6994    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6995            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6996            int userId) {
6997        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6998
6999        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7000            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7001                    candidates.size());
7002        }
7003
7004        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7005        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7006        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7007        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7008        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7009        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7010
7011        synchronized (mPackages) {
7012            final int count = candidates.size();
7013            // First, try to use linked apps. Partition the candidates into four lists:
7014            // one for the final results, one for the "do not use ever", one for "undefined status"
7015            // and finally one for "browser app type".
7016            for (int n=0; n<count; n++) {
7017                ResolveInfo info = candidates.get(n);
7018                String packageName = info.activityInfo.packageName;
7019                PackageSetting ps = mSettings.mPackages.get(packageName);
7020                if (ps != null) {
7021                    // Add to the special match all list (Browser use case)
7022                    if (info.handleAllWebDataURI) {
7023                        matchAllList.add(info);
7024                        continue;
7025                    }
7026                    // Try to get the status from User settings first
7027                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7028                    int status = (int)(packedStatus >> 32);
7029                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7030                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7031                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7032                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7033                                    + " : linkgen=" + linkGeneration);
7034                        }
7035                        // Use link-enabled generation as preferredOrder, i.e.
7036                        // prefer newly-enabled over earlier-enabled.
7037                        info.preferredOrder = linkGeneration;
7038                        alwaysList.add(info);
7039                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7040                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7041                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7042                        }
7043                        neverList.add(info);
7044                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7045                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7046                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7047                        }
7048                        alwaysAskList.add(info);
7049                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7050                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7051                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7052                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7053                        }
7054                        undefinedList.add(info);
7055                    }
7056                }
7057            }
7058
7059            // We'll want to include browser possibilities in a few cases
7060            boolean includeBrowser = false;
7061
7062            // First try to add the "always" resolution(s) for the current user, if any
7063            if (alwaysList.size() > 0) {
7064                result.addAll(alwaysList);
7065            } else {
7066                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7067                result.addAll(undefinedList);
7068                // Maybe add one for the other profile.
7069                if (xpDomainInfo != null && (
7070                        xpDomainInfo.bestDomainVerificationStatus
7071                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7072                    result.add(xpDomainInfo.resolveInfo);
7073                }
7074                includeBrowser = true;
7075            }
7076
7077            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7078            // If there were 'always' entries their preferred order has been set, so we also
7079            // back that off to make the alternatives equivalent
7080            if (alwaysAskList.size() > 0) {
7081                for (ResolveInfo i : result) {
7082                    i.preferredOrder = 0;
7083                }
7084                result.addAll(alwaysAskList);
7085                includeBrowser = true;
7086            }
7087
7088            if (includeBrowser) {
7089                // Also add browsers (all of them or only the default one)
7090                if (DEBUG_DOMAIN_VERIFICATION) {
7091                    Slog.v(TAG, "   ...including browsers in candidate set");
7092                }
7093                if ((matchFlags & MATCH_ALL) != 0) {
7094                    result.addAll(matchAllList);
7095                } else {
7096                    // Browser/generic handling case.  If there's a default browser, go straight
7097                    // to that (but only if there is no other higher-priority match).
7098                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7099                    int maxMatchPrio = 0;
7100                    ResolveInfo defaultBrowserMatch = null;
7101                    final int numCandidates = matchAllList.size();
7102                    for (int n = 0; n < numCandidates; n++) {
7103                        ResolveInfo info = matchAllList.get(n);
7104                        // track the highest overall match priority...
7105                        if (info.priority > maxMatchPrio) {
7106                            maxMatchPrio = info.priority;
7107                        }
7108                        // ...and the highest-priority default browser match
7109                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7110                            if (defaultBrowserMatch == null
7111                                    || (defaultBrowserMatch.priority < info.priority)) {
7112                                if (debug) {
7113                                    Slog.v(TAG, "Considering default browser match " + info);
7114                                }
7115                                defaultBrowserMatch = info;
7116                            }
7117                        }
7118                    }
7119                    if (defaultBrowserMatch != null
7120                            && defaultBrowserMatch.priority >= maxMatchPrio
7121                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7122                    {
7123                        if (debug) {
7124                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7125                        }
7126                        result.add(defaultBrowserMatch);
7127                    } else {
7128                        result.addAll(matchAllList);
7129                    }
7130                }
7131
7132                // If there is nothing selected, add all candidates and remove the ones that the user
7133                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7134                if (result.size() == 0) {
7135                    result.addAll(candidates);
7136                    result.removeAll(neverList);
7137                }
7138            }
7139        }
7140        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7141            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7142                    result.size());
7143            for (ResolveInfo info : result) {
7144                Slog.v(TAG, "  + " + info.activityInfo);
7145            }
7146        }
7147        return result;
7148    }
7149
7150    // Returns a packed value as a long:
7151    //
7152    // high 'int'-sized word: link status: undefined/ask/never/always.
7153    // low 'int'-sized word: relative priority among 'always' results.
7154    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7155        long result = ps.getDomainVerificationStatusForUser(userId);
7156        // if none available, get the master status
7157        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7158            if (ps.getIntentFilterVerificationInfo() != null) {
7159                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7160            }
7161        }
7162        return result;
7163    }
7164
7165    private ResolveInfo querySkipCurrentProfileIntents(
7166            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7167            int flags, int sourceUserId) {
7168        if (matchingFilters != null) {
7169            int size = matchingFilters.size();
7170            for (int i = 0; i < size; i ++) {
7171                CrossProfileIntentFilter filter = matchingFilters.get(i);
7172                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7173                    // Checking if there are activities in the target user that can handle the
7174                    // intent.
7175                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7176                            resolvedType, flags, sourceUserId);
7177                    if (resolveInfo != null) {
7178                        return resolveInfo;
7179                    }
7180                }
7181            }
7182        }
7183        return null;
7184    }
7185
7186    // Return matching ResolveInfo in target user if any.
7187    private ResolveInfo queryCrossProfileIntents(
7188            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7189            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7190        if (matchingFilters != null) {
7191            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7192            // match the same intent. For performance reasons, it is better not to
7193            // run queryIntent twice for the same userId
7194            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7195            int size = matchingFilters.size();
7196            for (int i = 0; i < size; i++) {
7197                CrossProfileIntentFilter filter = matchingFilters.get(i);
7198                int targetUserId = filter.getTargetUserId();
7199                boolean skipCurrentProfile =
7200                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7201                boolean skipCurrentProfileIfNoMatchFound =
7202                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7203                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7204                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7205                    // Checking if there are activities in the target user that can handle the
7206                    // intent.
7207                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7208                            resolvedType, flags, sourceUserId);
7209                    if (resolveInfo != null) return resolveInfo;
7210                    alreadyTriedUserIds.put(targetUserId, true);
7211                }
7212            }
7213        }
7214        return null;
7215    }
7216
7217    /**
7218     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7219     * will forward the intent to the filter's target user.
7220     * Otherwise, returns null.
7221     */
7222    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7223            String resolvedType, int flags, int sourceUserId) {
7224        int targetUserId = filter.getTargetUserId();
7225        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7226                resolvedType, flags, targetUserId);
7227        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7228            // If all the matches in the target profile are suspended, return null.
7229            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7230                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7231                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7232                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7233                            targetUserId);
7234                }
7235            }
7236        }
7237        return null;
7238    }
7239
7240    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7241            int sourceUserId, int targetUserId) {
7242        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7243        long ident = Binder.clearCallingIdentity();
7244        boolean targetIsProfile;
7245        try {
7246            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7247        } finally {
7248            Binder.restoreCallingIdentity(ident);
7249        }
7250        String className;
7251        if (targetIsProfile) {
7252            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7253        } else {
7254            className = FORWARD_INTENT_TO_PARENT;
7255        }
7256        ComponentName forwardingActivityComponentName = new ComponentName(
7257                mAndroidApplication.packageName, className);
7258        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7259                sourceUserId);
7260        if (!targetIsProfile) {
7261            forwardingActivityInfo.showUserIcon = targetUserId;
7262            forwardingResolveInfo.noResourceId = true;
7263        }
7264        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7265        forwardingResolveInfo.priority = 0;
7266        forwardingResolveInfo.preferredOrder = 0;
7267        forwardingResolveInfo.match = 0;
7268        forwardingResolveInfo.isDefault = true;
7269        forwardingResolveInfo.filter = filter;
7270        forwardingResolveInfo.targetUserId = targetUserId;
7271        return forwardingResolveInfo;
7272    }
7273
7274    @Override
7275    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7276            Intent[] specifics, String[] specificTypes, Intent intent,
7277            String resolvedType, int flags, int userId) {
7278        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7279                specificTypes, intent, resolvedType, flags, userId));
7280    }
7281
7282    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7283            Intent[] specifics, String[] specificTypes, Intent intent,
7284            String resolvedType, int flags, int userId) {
7285        if (!sUserManager.exists(userId)) return Collections.emptyList();
7286        final int callingUid = Binder.getCallingUid();
7287        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7288                false /*includeInstantApps*/);
7289        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7290                false /*requireFullPermission*/, false /*checkShell*/,
7291                "query intent activity options");
7292        final String resultsAction = intent.getAction();
7293
7294        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7295                | PackageManager.GET_RESOLVED_FILTER, userId);
7296
7297        if (DEBUG_INTENT_MATCHING) {
7298            Log.v(TAG, "Query " + intent + ": " + results);
7299        }
7300
7301        int specificsPos = 0;
7302        int N;
7303
7304        // todo: note that the algorithm used here is O(N^2).  This
7305        // isn't a problem in our current environment, but if we start running
7306        // into situations where we have more than 5 or 10 matches then this
7307        // should probably be changed to something smarter...
7308
7309        // First we go through and resolve each of the specific items
7310        // that were supplied, taking care of removing any corresponding
7311        // duplicate items in the generic resolve list.
7312        if (specifics != null) {
7313            for (int i=0; i<specifics.length; i++) {
7314                final Intent sintent = specifics[i];
7315                if (sintent == null) {
7316                    continue;
7317                }
7318
7319                if (DEBUG_INTENT_MATCHING) {
7320                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7321                }
7322
7323                String action = sintent.getAction();
7324                if (resultsAction != null && resultsAction.equals(action)) {
7325                    // If this action was explicitly requested, then don't
7326                    // remove things that have it.
7327                    action = null;
7328                }
7329
7330                ResolveInfo ri = null;
7331                ActivityInfo ai = null;
7332
7333                ComponentName comp = sintent.getComponent();
7334                if (comp == null) {
7335                    ri = resolveIntent(
7336                        sintent,
7337                        specificTypes != null ? specificTypes[i] : null,
7338                            flags, userId);
7339                    if (ri == null) {
7340                        continue;
7341                    }
7342                    if (ri == mResolveInfo) {
7343                        // ACK!  Must do something better with this.
7344                    }
7345                    ai = ri.activityInfo;
7346                    comp = new ComponentName(ai.applicationInfo.packageName,
7347                            ai.name);
7348                } else {
7349                    ai = getActivityInfo(comp, flags, userId);
7350                    if (ai == null) {
7351                        continue;
7352                    }
7353                }
7354
7355                // Look for any generic query activities that are duplicates
7356                // of this specific one, and remove them from the results.
7357                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7358                N = results.size();
7359                int j;
7360                for (j=specificsPos; j<N; j++) {
7361                    ResolveInfo sri = results.get(j);
7362                    if ((sri.activityInfo.name.equals(comp.getClassName())
7363                            && sri.activityInfo.applicationInfo.packageName.equals(
7364                                    comp.getPackageName()))
7365                        || (action != null && sri.filter.matchAction(action))) {
7366                        results.remove(j);
7367                        if (DEBUG_INTENT_MATCHING) Log.v(
7368                            TAG, "Removing duplicate item from " + j
7369                            + " due to specific " + specificsPos);
7370                        if (ri == null) {
7371                            ri = sri;
7372                        }
7373                        j--;
7374                        N--;
7375                    }
7376                }
7377
7378                // Add this specific item to its proper place.
7379                if (ri == null) {
7380                    ri = new ResolveInfo();
7381                    ri.activityInfo = ai;
7382                }
7383                results.add(specificsPos, ri);
7384                ri.specificIndex = i;
7385                specificsPos++;
7386            }
7387        }
7388
7389        // Now we go through the remaining generic results and remove any
7390        // duplicate actions that are found here.
7391        N = results.size();
7392        for (int i=specificsPos; i<N-1; i++) {
7393            final ResolveInfo rii = results.get(i);
7394            if (rii.filter == null) {
7395                continue;
7396            }
7397
7398            // Iterate over all of the actions of this result's intent
7399            // filter...  typically this should be just one.
7400            final Iterator<String> it = rii.filter.actionsIterator();
7401            if (it == null) {
7402                continue;
7403            }
7404            while (it.hasNext()) {
7405                final String action = it.next();
7406                if (resultsAction != null && resultsAction.equals(action)) {
7407                    // If this action was explicitly requested, then don't
7408                    // remove things that have it.
7409                    continue;
7410                }
7411                for (int j=i+1; j<N; j++) {
7412                    final ResolveInfo rij = results.get(j);
7413                    if (rij.filter != null && rij.filter.hasAction(action)) {
7414                        results.remove(j);
7415                        if (DEBUG_INTENT_MATCHING) Log.v(
7416                            TAG, "Removing duplicate item from " + j
7417                            + " due to action " + action + " at " + i);
7418                        j--;
7419                        N--;
7420                    }
7421                }
7422            }
7423
7424            // If the caller didn't request filter information, drop it now
7425            // so we don't have to marshall/unmarshall it.
7426            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7427                rii.filter = null;
7428            }
7429        }
7430
7431        // Filter out the caller activity if so requested.
7432        if (caller != null) {
7433            N = results.size();
7434            for (int i=0; i<N; i++) {
7435                ActivityInfo ainfo = results.get(i).activityInfo;
7436                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7437                        && caller.getClassName().equals(ainfo.name)) {
7438                    results.remove(i);
7439                    break;
7440                }
7441            }
7442        }
7443
7444        // If the caller didn't request filter information,
7445        // drop them now so we don't have to
7446        // marshall/unmarshall it.
7447        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7448            N = results.size();
7449            for (int i=0; i<N; i++) {
7450                results.get(i).filter = null;
7451            }
7452        }
7453
7454        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7455        return results;
7456    }
7457
7458    @Override
7459    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7460            String resolvedType, int flags, int userId) {
7461        return new ParceledListSlice<>(
7462                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7463                        false /*allowDynamicSplits*/));
7464    }
7465
7466    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7467            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7468        if (!sUserManager.exists(userId)) return Collections.emptyList();
7469        final int callingUid = Binder.getCallingUid();
7470        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7471                false /*requireFullPermission*/, false /*checkShell*/,
7472                "query intent receivers");
7473        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7474        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7475                false /*includeInstantApps*/);
7476        ComponentName comp = intent.getComponent();
7477        if (comp == null) {
7478            if (intent.getSelector() != null) {
7479                intent = intent.getSelector();
7480                comp = intent.getComponent();
7481            }
7482        }
7483        if (comp != null) {
7484            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7485            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7486            if (ai != null) {
7487                // When specifying an explicit component, we prevent the activity from being
7488                // used when either 1) the calling package is normal and the activity is within
7489                // an instant application or 2) the calling package is ephemeral and the
7490                // activity is not visible to instant applications.
7491                final boolean matchInstantApp =
7492                        (flags & PackageManager.MATCH_INSTANT) != 0;
7493                final boolean matchVisibleToInstantAppOnly =
7494                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7495                final boolean matchExplicitlyVisibleOnly =
7496                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7497                final boolean isCallerInstantApp =
7498                        instantAppPkgName != null;
7499                final boolean isTargetSameInstantApp =
7500                        comp.getPackageName().equals(instantAppPkgName);
7501                final boolean isTargetInstantApp =
7502                        (ai.applicationInfo.privateFlags
7503                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7504                final boolean isTargetVisibleToInstantApp =
7505                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7506                final boolean isTargetExplicitlyVisibleToInstantApp =
7507                        isTargetVisibleToInstantApp
7508                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7509                final boolean isTargetHiddenFromInstantApp =
7510                        !isTargetVisibleToInstantApp
7511                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7512                final boolean blockResolution =
7513                        !isTargetSameInstantApp
7514                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7515                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7516                                        && isTargetHiddenFromInstantApp));
7517                if (!blockResolution) {
7518                    ResolveInfo ri = new ResolveInfo();
7519                    ri.activityInfo = ai;
7520                    list.add(ri);
7521                }
7522            }
7523            return applyPostResolutionFilter(
7524                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7525        }
7526
7527        // reader
7528        synchronized (mPackages) {
7529            String pkgName = intent.getPackage();
7530            if (pkgName == null) {
7531                final List<ResolveInfo> result =
7532                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7533                return applyPostResolutionFilter(
7534                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7535            }
7536            final PackageParser.Package pkg = mPackages.get(pkgName);
7537            if (pkg != null) {
7538                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7539                        intent, resolvedType, flags, pkg.receivers, userId);
7540                return applyPostResolutionFilter(
7541                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7542            }
7543            return Collections.emptyList();
7544        }
7545    }
7546
7547    @Override
7548    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7549        final int callingUid = Binder.getCallingUid();
7550        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7551    }
7552
7553    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7554            int userId, int callingUid) {
7555        if (!sUserManager.exists(userId)) return null;
7556        flags = updateFlagsForResolve(
7557                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7558        List<ResolveInfo> query = queryIntentServicesInternal(
7559                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7560        if (query != null) {
7561            if (query.size() >= 1) {
7562                // If there is more than one service with the same priority,
7563                // just arbitrarily pick the first one.
7564                return query.get(0);
7565            }
7566        }
7567        return null;
7568    }
7569
7570    @Override
7571    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7572            String resolvedType, int flags, int userId) {
7573        final int callingUid = Binder.getCallingUid();
7574        return new ParceledListSlice<>(queryIntentServicesInternal(
7575                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7576    }
7577
7578    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7579            String resolvedType, int flags, int userId, int callingUid,
7580            boolean includeInstantApps) {
7581        if (!sUserManager.exists(userId)) return Collections.emptyList();
7582        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7583                false /*requireFullPermission*/, false /*checkShell*/,
7584                "query intent receivers");
7585        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7586        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7587        ComponentName comp = intent.getComponent();
7588        if (comp == null) {
7589            if (intent.getSelector() != null) {
7590                intent = intent.getSelector();
7591                comp = intent.getComponent();
7592            }
7593        }
7594        if (comp != null) {
7595            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7596            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7597            if (si != null) {
7598                // When specifying an explicit component, we prevent the service from being
7599                // used when either 1) the service is in an instant application and the
7600                // caller is not the same instant application or 2) the calling package is
7601                // ephemeral and the activity is not visible to ephemeral applications.
7602                final boolean matchInstantApp =
7603                        (flags & PackageManager.MATCH_INSTANT) != 0;
7604                final boolean matchVisibleToInstantAppOnly =
7605                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7606                final boolean isCallerInstantApp =
7607                        instantAppPkgName != null;
7608                final boolean isTargetSameInstantApp =
7609                        comp.getPackageName().equals(instantAppPkgName);
7610                final boolean isTargetInstantApp =
7611                        (si.applicationInfo.privateFlags
7612                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7613                final boolean isTargetHiddenFromInstantApp =
7614                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7615                final boolean blockResolution =
7616                        !isTargetSameInstantApp
7617                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7618                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7619                                        && isTargetHiddenFromInstantApp));
7620                if (!blockResolution) {
7621                    final ResolveInfo ri = new ResolveInfo();
7622                    ri.serviceInfo = si;
7623                    list.add(ri);
7624                }
7625            }
7626            return list;
7627        }
7628
7629        // reader
7630        synchronized (mPackages) {
7631            String pkgName = intent.getPackage();
7632            if (pkgName == null) {
7633                return applyPostServiceResolutionFilter(
7634                        mServices.queryIntent(intent, resolvedType, flags, userId),
7635                        instantAppPkgName);
7636            }
7637            final PackageParser.Package pkg = mPackages.get(pkgName);
7638            if (pkg != null) {
7639                return applyPostServiceResolutionFilter(
7640                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7641                                userId),
7642                        instantAppPkgName);
7643            }
7644            return Collections.emptyList();
7645        }
7646    }
7647
7648    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7649            String instantAppPkgName) {
7650        if (instantAppPkgName == null) {
7651            return resolveInfos;
7652        }
7653        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7654            final ResolveInfo info = resolveInfos.get(i);
7655            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7656            // allow services that are defined in the provided package
7657            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7658                if (info.serviceInfo.splitName != null
7659                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7660                                info.serviceInfo.splitName)) {
7661                    // requested service is defined in a split that hasn't been installed yet.
7662                    // add the installer to the resolve list
7663                    if (DEBUG_INSTANT) {
7664                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7665                    }
7666                    final ResolveInfo installerInfo = new ResolveInfo(
7667                            mInstantAppInstallerInfo);
7668                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7669                            null /* installFailureActivity */,
7670                            info.serviceInfo.packageName,
7671                            info.serviceInfo.applicationInfo.versionCode,
7672                            info.serviceInfo.splitName);
7673                    // add a non-generic filter
7674                    installerInfo.filter = new IntentFilter();
7675                    // load resources from the correct package
7676                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7677                    resolveInfos.set(i, installerInfo);
7678                }
7679                continue;
7680            }
7681            // allow services that have been explicitly exposed to ephemeral apps
7682            if (!isEphemeralApp
7683                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7684                continue;
7685            }
7686            resolveInfos.remove(i);
7687        }
7688        return resolveInfos;
7689    }
7690
7691    @Override
7692    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7693            String resolvedType, int flags, int userId) {
7694        return new ParceledListSlice<>(
7695                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7696    }
7697
7698    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7699            Intent intent, String resolvedType, int flags, int userId) {
7700        if (!sUserManager.exists(userId)) return Collections.emptyList();
7701        final int callingUid = Binder.getCallingUid();
7702        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7703        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7704                false /*includeInstantApps*/);
7705        ComponentName comp = intent.getComponent();
7706        if (comp == null) {
7707            if (intent.getSelector() != null) {
7708                intent = intent.getSelector();
7709                comp = intent.getComponent();
7710            }
7711        }
7712        if (comp != null) {
7713            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7714            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7715            if (pi != null) {
7716                // When specifying an explicit component, we prevent the provider from being
7717                // used when either 1) the provider is in an instant application and the
7718                // caller is not the same instant application or 2) the calling package is an
7719                // instant application and the provider is not visible to instant applications.
7720                final boolean matchInstantApp =
7721                        (flags & PackageManager.MATCH_INSTANT) != 0;
7722                final boolean matchVisibleToInstantAppOnly =
7723                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7724                final boolean isCallerInstantApp =
7725                        instantAppPkgName != null;
7726                final boolean isTargetSameInstantApp =
7727                        comp.getPackageName().equals(instantAppPkgName);
7728                final boolean isTargetInstantApp =
7729                        (pi.applicationInfo.privateFlags
7730                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7731                final boolean isTargetHiddenFromInstantApp =
7732                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7733                final boolean blockResolution =
7734                        !isTargetSameInstantApp
7735                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7736                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7737                                        && isTargetHiddenFromInstantApp));
7738                if (!blockResolution) {
7739                    final ResolveInfo ri = new ResolveInfo();
7740                    ri.providerInfo = pi;
7741                    list.add(ri);
7742                }
7743            }
7744            return list;
7745        }
7746
7747        // reader
7748        synchronized (mPackages) {
7749            String pkgName = intent.getPackage();
7750            if (pkgName == null) {
7751                return applyPostContentProviderResolutionFilter(
7752                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7753                        instantAppPkgName);
7754            }
7755            final PackageParser.Package pkg = mPackages.get(pkgName);
7756            if (pkg != null) {
7757                return applyPostContentProviderResolutionFilter(
7758                        mProviders.queryIntentForPackage(
7759                        intent, resolvedType, flags, pkg.providers, userId),
7760                        instantAppPkgName);
7761            }
7762            return Collections.emptyList();
7763        }
7764    }
7765
7766    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7767            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7768        if (instantAppPkgName == null) {
7769            return resolveInfos;
7770        }
7771        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7772            final ResolveInfo info = resolveInfos.get(i);
7773            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7774            // allow providers that are defined in the provided package
7775            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7776                if (info.providerInfo.splitName != null
7777                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7778                                info.providerInfo.splitName)) {
7779                    // requested provider is defined in a split that hasn't been installed yet.
7780                    // add the installer to the resolve list
7781                    if (DEBUG_INSTANT) {
7782                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7783                    }
7784                    final ResolveInfo installerInfo = new ResolveInfo(
7785                            mInstantAppInstallerInfo);
7786                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7787                            null /*failureActivity*/,
7788                            info.providerInfo.packageName,
7789                            info.providerInfo.applicationInfo.versionCode,
7790                            info.providerInfo.splitName);
7791                    // add a non-generic filter
7792                    installerInfo.filter = new IntentFilter();
7793                    // load resources from the correct package
7794                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7795                    resolveInfos.set(i, installerInfo);
7796                }
7797                continue;
7798            }
7799            // allow providers that have been explicitly exposed to instant applications
7800            if (!isEphemeralApp
7801                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7802                continue;
7803            }
7804            resolveInfos.remove(i);
7805        }
7806        return resolveInfos;
7807    }
7808
7809    @Override
7810    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7811        final int callingUid = Binder.getCallingUid();
7812        if (getInstantAppPackageName(callingUid) != null) {
7813            return ParceledListSlice.emptyList();
7814        }
7815        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7816        flags = updateFlagsForPackage(flags, userId, null);
7817        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7818        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7819                true /* requireFullPermission */, false /* checkShell */,
7820                "get installed packages");
7821
7822        // writer
7823        synchronized (mPackages) {
7824            ArrayList<PackageInfo> list;
7825            if (listUninstalled) {
7826                list = new ArrayList<>(mSettings.mPackages.size());
7827                for (PackageSetting ps : mSettings.mPackages.values()) {
7828                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7829                        continue;
7830                    }
7831                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7832                        continue;
7833                    }
7834                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7835                    if (pi != null) {
7836                        list.add(pi);
7837                    }
7838                }
7839            } else {
7840                list = new ArrayList<>(mPackages.size());
7841                for (PackageParser.Package p : mPackages.values()) {
7842                    final PackageSetting ps = (PackageSetting) p.mExtras;
7843                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7844                        continue;
7845                    }
7846                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7847                        continue;
7848                    }
7849                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7850                            p.mExtras, flags, userId);
7851                    if (pi != null) {
7852                        list.add(pi);
7853                    }
7854                }
7855            }
7856
7857            return new ParceledListSlice<>(list);
7858        }
7859    }
7860
7861    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7862            String[] permissions, boolean[] tmp, int flags, int userId) {
7863        int numMatch = 0;
7864        final PermissionsState permissionsState = ps.getPermissionsState();
7865        for (int i=0; i<permissions.length; i++) {
7866            final String permission = permissions[i];
7867            if (permissionsState.hasPermission(permission, userId)) {
7868                tmp[i] = true;
7869                numMatch++;
7870            } else {
7871                tmp[i] = false;
7872            }
7873        }
7874        if (numMatch == 0) {
7875            return;
7876        }
7877        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7878
7879        // The above might return null in cases of uninstalled apps or install-state
7880        // skew across users/profiles.
7881        if (pi != null) {
7882            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7883                if (numMatch == permissions.length) {
7884                    pi.requestedPermissions = permissions;
7885                } else {
7886                    pi.requestedPermissions = new String[numMatch];
7887                    numMatch = 0;
7888                    for (int i=0; i<permissions.length; i++) {
7889                        if (tmp[i]) {
7890                            pi.requestedPermissions[numMatch] = permissions[i];
7891                            numMatch++;
7892                        }
7893                    }
7894                }
7895            }
7896            list.add(pi);
7897        }
7898    }
7899
7900    @Override
7901    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7902            String[] permissions, int flags, int userId) {
7903        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7904        flags = updateFlagsForPackage(flags, userId, permissions);
7905        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7906                true /* requireFullPermission */, false /* checkShell */,
7907                "get packages holding permissions");
7908        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7909
7910        // writer
7911        synchronized (mPackages) {
7912            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7913            boolean[] tmpBools = new boolean[permissions.length];
7914            if (listUninstalled) {
7915                for (PackageSetting ps : mSettings.mPackages.values()) {
7916                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7917                            userId);
7918                }
7919            } else {
7920                for (PackageParser.Package pkg : mPackages.values()) {
7921                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7922                    if (ps != null) {
7923                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7924                                userId);
7925                    }
7926                }
7927            }
7928
7929            return new ParceledListSlice<PackageInfo>(list);
7930        }
7931    }
7932
7933    @Override
7934    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7935        final int callingUid = Binder.getCallingUid();
7936        if (getInstantAppPackageName(callingUid) != null) {
7937            return ParceledListSlice.emptyList();
7938        }
7939        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7940        flags = updateFlagsForApplication(flags, userId, null);
7941        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7942
7943        // writer
7944        synchronized (mPackages) {
7945            ArrayList<ApplicationInfo> list;
7946            if (listUninstalled) {
7947                list = new ArrayList<>(mSettings.mPackages.size());
7948                for (PackageSetting ps : mSettings.mPackages.values()) {
7949                    ApplicationInfo ai;
7950                    int effectiveFlags = flags;
7951                    if (ps.isSystem()) {
7952                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7953                    }
7954                    if (ps.pkg != null) {
7955                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7956                            continue;
7957                        }
7958                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7959                            continue;
7960                        }
7961                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7962                                ps.readUserState(userId), userId);
7963                        if (ai != null) {
7964                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7965                        }
7966                    } else {
7967                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7968                        // and already converts to externally visible package name
7969                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7970                                callingUid, effectiveFlags, userId);
7971                    }
7972                    if (ai != null) {
7973                        list.add(ai);
7974                    }
7975                }
7976            } else {
7977                list = new ArrayList<>(mPackages.size());
7978                for (PackageParser.Package p : mPackages.values()) {
7979                    if (p.mExtras != null) {
7980                        PackageSetting ps = (PackageSetting) p.mExtras;
7981                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7982                            continue;
7983                        }
7984                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7985                            continue;
7986                        }
7987                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7988                                ps.readUserState(userId), userId);
7989                        if (ai != null) {
7990                            ai.packageName = resolveExternalPackageNameLPr(p);
7991                            list.add(ai);
7992                        }
7993                    }
7994                }
7995            }
7996
7997            return new ParceledListSlice<>(list);
7998        }
7999    }
8000
8001    @Override
8002    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8003        if (HIDE_EPHEMERAL_APIS) {
8004            return null;
8005        }
8006        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8007            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8008                    "getEphemeralApplications");
8009        }
8010        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8011                true /* requireFullPermission */, false /* checkShell */,
8012                "getEphemeralApplications");
8013        synchronized (mPackages) {
8014            List<InstantAppInfo> instantApps = mInstantAppRegistry
8015                    .getInstantAppsLPr(userId);
8016            if (instantApps != null) {
8017                return new ParceledListSlice<>(instantApps);
8018            }
8019        }
8020        return null;
8021    }
8022
8023    @Override
8024    public boolean isInstantApp(String packageName, int userId) {
8025        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8026                true /* requireFullPermission */, false /* checkShell */,
8027                "isInstantApp");
8028        if (HIDE_EPHEMERAL_APIS) {
8029            return false;
8030        }
8031
8032        synchronized (mPackages) {
8033            int callingUid = Binder.getCallingUid();
8034            if (Process.isIsolated(callingUid)) {
8035                callingUid = mIsolatedOwners.get(callingUid);
8036            }
8037            final PackageSetting ps = mSettings.mPackages.get(packageName);
8038            PackageParser.Package pkg = mPackages.get(packageName);
8039            final boolean returnAllowed =
8040                    ps != null
8041                    && (isCallerSameApp(packageName, callingUid)
8042                            || canViewInstantApps(callingUid, userId)
8043                            || mInstantAppRegistry.isInstantAccessGranted(
8044                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8045            if (returnAllowed) {
8046                return ps.getInstantApp(userId);
8047            }
8048        }
8049        return false;
8050    }
8051
8052    @Override
8053    public byte[] getInstantAppCookie(String packageName, int userId) {
8054        if (HIDE_EPHEMERAL_APIS) {
8055            return null;
8056        }
8057
8058        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8059                true /* requireFullPermission */, false /* checkShell */,
8060                "getInstantAppCookie");
8061        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8062            return null;
8063        }
8064        synchronized (mPackages) {
8065            return mInstantAppRegistry.getInstantAppCookieLPw(
8066                    packageName, userId);
8067        }
8068    }
8069
8070    @Override
8071    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8072        if (HIDE_EPHEMERAL_APIS) {
8073            return true;
8074        }
8075
8076        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8077                true /* requireFullPermission */, true /* checkShell */,
8078                "setInstantAppCookie");
8079        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8080            return false;
8081        }
8082        synchronized (mPackages) {
8083            return mInstantAppRegistry.setInstantAppCookieLPw(
8084                    packageName, cookie, userId);
8085        }
8086    }
8087
8088    @Override
8089    public Bitmap getInstantAppIcon(String packageName, int userId) {
8090        if (HIDE_EPHEMERAL_APIS) {
8091            return null;
8092        }
8093
8094        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8095            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8096                    "getInstantAppIcon");
8097        }
8098        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8099                true /* requireFullPermission */, false /* checkShell */,
8100                "getInstantAppIcon");
8101
8102        synchronized (mPackages) {
8103            return mInstantAppRegistry.getInstantAppIconLPw(
8104                    packageName, userId);
8105        }
8106    }
8107
8108    private boolean isCallerSameApp(String packageName, int uid) {
8109        PackageParser.Package pkg = mPackages.get(packageName);
8110        return pkg != null
8111                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8112    }
8113
8114    @Override
8115    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8116        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8117            return ParceledListSlice.emptyList();
8118        }
8119        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8120    }
8121
8122    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8123        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8124
8125        // reader
8126        synchronized (mPackages) {
8127            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8128            final int userId = UserHandle.getCallingUserId();
8129            while (i.hasNext()) {
8130                final PackageParser.Package p = i.next();
8131                if (p.applicationInfo == null) continue;
8132
8133                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8134                        && !p.applicationInfo.isDirectBootAware();
8135                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8136                        && p.applicationInfo.isDirectBootAware();
8137
8138                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8139                        && (!mSafeMode || isSystemApp(p))
8140                        && (matchesUnaware || matchesAware)) {
8141                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8142                    if (ps != null) {
8143                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8144                                ps.readUserState(userId), userId);
8145                        if (ai != null) {
8146                            finalList.add(ai);
8147                        }
8148                    }
8149                }
8150            }
8151        }
8152
8153        return finalList;
8154    }
8155
8156    @Override
8157    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8158        return resolveContentProviderInternal(name, flags, userId);
8159    }
8160
8161    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8162        if (!sUserManager.exists(userId)) return null;
8163        flags = updateFlagsForComponent(flags, userId, name);
8164        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8165        // reader
8166        synchronized (mPackages) {
8167            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8168            PackageSetting ps = provider != null
8169                    ? mSettings.mPackages.get(provider.owner.packageName)
8170                    : null;
8171            if (ps != null) {
8172                final boolean isInstantApp = ps.getInstantApp(userId);
8173                // normal application; filter out instant application provider
8174                if (instantAppPkgName == null && isInstantApp) {
8175                    return null;
8176                }
8177                // instant application; filter out other instant applications
8178                if (instantAppPkgName != null
8179                        && isInstantApp
8180                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8181                    return null;
8182                }
8183                // instant application; filter out non-exposed provider
8184                if (instantAppPkgName != null
8185                        && !isInstantApp
8186                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8187                    return null;
8188                }
8189                // provider not enabled
8190                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8191                    return null;
8192                }
8193                return PackageParser.generateProviderInfo(
8194                        provider, flags, ps.readUserState(userId), userId);
8195            }
8196            return null;
8197        }
8198    }
8199
8200    /**
8201     * @deprecated
8202     */
8203    @Deprecated
8204    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8205        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8206            return;
8207        }
8208        // reader
8209        synchronized (mPackages) {
8210            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8211                    .entrySet().iterator();
8212            final int userId = UserHandle.getCallingUserId();
8213            while (i.hasNext()) {
8214                Map.Entry<String, PackageParser.Provider> entry = i.next();
8215                PackageParser.Provider p = entry.getValue();
8216                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8217
8218                if (ps != null && p.syncable
8219                        && (!mSafeMode || (p.info.applicationInfo.flags
8220                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8221                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8222                            ps.readUserState(userId), userId);
8223                    if (info != null) {
8224                        outNames.add(entry.getKey());
8225                        outInfo.add(info);
8226                    }
8227                }
8228            }
8229        }
8230    }
8231
8232    @Override
8233    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8234            int uid, int flags, String metaDataKey) {
8235        final int callingUid = Binder.getCallingUid();
8236        final int userId = processName != null ? UserHandle.getUserId(uid)
8237                : UserHandle.getCallingUserId();
8238        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8239        flags = updateFlagsForComponent(flags, userId, processName);
8240        ArrayList<ProviderInfo> finalList = null;
8241        // reader
8242        synchronized (mPackages) {
8243            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8244            while (i.hasNext()) {
8245                final PackageParser.Provider p = i.next();
8246                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8247                if (ps != null && p.info.authority != null
8248                        && (processName == null
8249                                || (p.info.processName.equals(processName)
8250                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8251                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8252
8253                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8254                    // parameter.
8255                    if (metaDataKey != null
8256                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8257                        continue;
8258                    }
8259                    final ComponentName component =
8260                            new ComponentName(p.info.packageName, p.info.name);
8261                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8262                        continue;
8263                    }
8264                    if (finalList == null) {
8265                        finalList = new ArrayList<ProviderInfo>(3);
8266                    }
8267                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8268                            ps.readUserState(userId), userId);
8269                    if (info != null) {
8270                        finalList.add(info);
8271                    }
8272                }
8273            }
8274        }
8275
8276        if (finalList != null) {
8277            Collections.sort(finalList, mProviderInitOrderSorter);
8278            return new ParceledListSlice<ProviderInfo>(finalList);
8279        }
8280
8281        return ParceledListSlice.emptyList();
8282    }
8283
8284    @Override
8285    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8286        // reader
8287        synchronized (mPackages) {
8288            final int callingUid = Binder.getCallingUid();
8289            final int callingUserId = UserHandle.getUserId(callingUid);
8290            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8291            if (ps == null) return null;
8292            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8293                return null;
8294            }
8295            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8296            return PackageParser.generateInstrumentationInfo(i, flags);
8297        }
8298    }
8299
8300    @Override
8301    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8302            String targetPackage, int flags) {
8303        final int callingUid = Binder.getCallingUid();
8304        final int callingUserId = UserHandle.getUserId(callingUid);
8305        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8306        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8307            return ParceledListSlice.emptyList();
8308        }
8309        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8310    }
8311
8312    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8313            int flags) {
8314        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8315
8316        // reader
8317        synchronized (mPackages) {
8318            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8319            while (i.hasNext()) {
8320                final PackageParser.Instrumentation p = i.next();
8321                if (targetPackage == null
8322                        || targetPackage.equals(p.info.targetPackage)) {
8323                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8324                            flags);
8325                    if (ii != null) {
8326                        finalList.add(ii);
8327                    }
8328                }
8329            }
8330        }
8331
8332        return finalList;
8333    }
8334
8335    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8336        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8337        try {
8338            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8339        } finally {
8340            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8341        }
8342    }
8343
8344    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8345        final File[] files = scanDir.listFiles();
8346        if (ArrayUtils.isEmpty(files)) {
8347            Log.d(TAG, "No files in app dir " + scanDir);
8348            return;
8349        }
8350
8351        if (DEBUG_PACKAGE_SCANNING) {
8352            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8353                    + " flags=0x" + Integer.toHexString(parseFlags));
8354        }
8355        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8356                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8357                mParallelPackageParserCallback)) {
8358            // Submit files for parsing in parallel
8359            int fileCount = 0;
8360            for (File file : files) {
8361                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8362                        && !PackageInstallerService.isStageName(file.getName());
8363                if (!isPackage) {
8364                    // Ignore entries which are not packages
8365                    continue;
8366                }
8367                parallelPackageParser.submit(file, parseFlags);
8368                fileCount++;
8369            }
8370
8371            // Process results one by one
8372            for (; fileCount > 0; fileCount--) {
8373                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8374                Throwable throwable = parseResult.throwable;
8375                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8376
8377                if (throwable == null) {
8378                    // TODO(toddke): move lower in the scan chain
8379                    // Static shared libraries have synthetic package names
8380                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8381                        renameStaticSharedLibraryPackage(parseResult.pkg);
8382                    }
8383                    try {
8384                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8385                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8386                                    currentTime, null);
8387                        }
8388                    } catch (PackageManagerException e) {
8389                        errorCode = e.error;
8390                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8391                    }
8392                } else if (throwable instanceof PackageParser.PackageParserException) {
8393                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8394                            throwable;
8395                    errorCode = e.error;
8396                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8397                } else {
8398                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8399                            + parseResult.scanFile, throwable);
8400                }
8401
8402                // Delete invalid userdata apps
8403                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8404                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8405                    logCriticalInfo(Log.WARN,
8406                            "Deleting invalid package at " + parseResult.scanFile);
8407                    removeCodePathLI(parseResult.scanFile);
8408                }
8409            }
8410        }
8411    }
8412
8413    public static void reportSettingsProblem(int priority, String msg) {
8414        logCriticalInfo(priority, msg);
8415    }
8416
8417    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8418            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8419        // When upgrading from pre-N MR1, verify the package time stamp using the package
8420        // directory and not the APK file.
8421        final long lastModifiedTime = mIsPreNMR1Upgrade
8422                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8423        if (ps != null && !forceCollect
8424                && ps.codePathString.equals(pkg.codePath)
8425                && ps.timeStamp == lastModifiedTime
8426                && !isCompatSignatureUpdateNeeded(pkg)
8427                && !isRecoverSignatureUpdateNeeded(pkg)) {
8428            if (ps.signatures.mSigningDetails.signatures != null
8429                    && ps.signatures.mSigningDetails.signatures.length != 0
8430                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8431                            != SignatureSchemeVersion.UNKNOWN) {
8432                // Optimization: reuse the existing cached signing data
8433                // if the package appears to be unchanged.
8434                pkg.mSigningDetails =
8435                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8436                return;
8437            }
8438
8439            Slog.w(TAG, "PackageSetting for " + ps.name
8440                    + " is missing signatures.  Collecting certs again to recover them.");
8441        } else {
8442            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8443                    (forceCollect ? " (forced)" : ""));
8444        }
8445
8446        try {
8447            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8448            PackageParser.collectCertificates(pkg, skipVerify);
8449        } catch (PackageParserException e) {
8450            throw PackageManagerException.from(e);
8451        } finally {
8452            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8453        }
8454    }
8455
8456    /**
8457     *  Traces a package scan.
8458     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8459     */
8460    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8461            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8462        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8463        try {
8464            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8465        } finally {
8466            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8467        }
8468    }
8469
8470    /**
8471     *  Scans a package and returns the newly parsed package.
8472     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8473     */
8474    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8475            long currentTime, UserHandle user) throws PackageManagerException {
8476        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8477        PackageParser pp = new PackageParser();
8478        pp.setSeparateProcesses(mSeparateProcesses);
8479        pp.setOnlyCoreApps(mOnlyCore);
8480        pp.setDisplayMetrics(mMetrics);
8481        pp.setCallback(mPackageParserCallback);
8482
8483        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8484        final PackageParser.Package pkg;
8485        try {
8486            pkg = pp.parsePackage(scanFile, parseFlags);
8487        } catch (PackageParserException e) {
8488            throw PackageManagerException.from(e);
8489        } finally {
8490            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8491        }
8492
8493        // Static shared libraries have synthetic package names
8494        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8495            renameStaticSharedLibraryPackage(pkg);
8496        }
8497
8498        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8499    }
8500
8501    /**
8502     *  Scans a package and returns the newly parsed package.
8503     *  @throws PackageManagerException on a parse error.
8504     */
8505    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8506            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8507            @Nullable UserHandle user)
8508                    throws PackageManagerException {
8509        // If the package has children and this is the first dive in the function
8510        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8511        // packages (parent and children) would be successfully scanned before the
8512        // actual scan since scanning mutates internal state and we want to atomically
8513        // install the package and its children.
8514        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8515            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8516                scanFlags |= SCAN_CHECK_ONLY;
8517            }
8518        } else {
8519            scanFlags &= ~SCAN_CHECK_ONLY;
8520        }
8521
8522        // Scan the parent
8523        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8524                scanFlags, currentTime, user);
8525
8526        // Scan the children
8527        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8528        for (int i = 0; i < childCount; i++) {
8529            PackageParser.Package childPackage = pkg.childPackages.get(i);
8530            addForInitLI(childPackage, parseFlags, scanFlags,
8531                    currentTime, user);
8532        }
8533
8534
8535        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8536            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8537        }
8538
8539        return scannedPkg;
8540    }
8541
8542    /**
8543     * Returns if full apk verification can be skipped for the whole package, including the splits.
8544     */
8545    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8546        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8547            return false;
8548        }
8549        // TODO: Allow base and splits to be verified individually.
8550        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8551            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8552                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8553                    return false;
8554                }
8555            }
8556        }
8557        return true;
8558    }
8559
8560    /**
8561     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8562     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8563     * match one in a trusted source, and should be done separately.
8564     */
8565    private boolean canSkipFullApkVerification(String apkPath) {
8566        byte[] rootHashObserved = null;
8567        try {
8568            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8569            if (rootHashObserved == null) {
8570                return false;  // APK does not contain Merkle tree root hash.
8571            }
8572            synchronized (mInstallLock) {
8573                // Returns whether the observed root hash matches what kernel has.
8574                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8575                return true;
8576            }
8577        } catch (InstallerException | IOException | DigestException |
8578                NoSuchAlgorithmException e) {
8579            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8580        }
8581        return false;
8582    }
8583
8584    /**
8585     * Adds a new package to the internal data structures during platform initialization.
8586     * <p>After adding, the package is known to the system and available for querying.
8587     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8588     * etc...], additional checks are performed. Basic verification [such as ensuring
8589     * matching signatures, checking version codes, etc...] occurs if the package is
8590     * identical to a previously known package. If the package fails a signature check,
8591     * the version installed on /data will be removed. If the version of the new package
8592     * is less than or equal than the version on /data, it will be ignored.
8593     * <p>Regardless of the package location, the results are applied to the internal
8594     * structures and the package is made available to the rest of the system.
8595     * <p>NOTE: The return value should be removed. It's the passed in package object.
8596     */
8597    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8598            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8599            @Nullable UserHandle user)
8600                    throws PackageManagerException {
8601        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8602        final String renamedPkgName;
8603        final PackageSetting disabledPkgSetting;
8604        final boolean isSystemPkgUpdated;
8605        final boolean pkgAlreadyExists;
8606        PackageSetting pkgSetting;
8607
8608        // NOTE: installPackageLI() has the same code to setup the package's
8609        // application info. This probably should be done lower in the call
8610        // stack [such as scanPackageOnly()]. However, we verify the application
8611        // info prior to that [in scanPackageNew()] and thus have to setup
8612        // the application info early.
8613        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8614        pkg.setApplicationInfoCodePath(pkg.codePath);
8615        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8616        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8617        pkg.setApplicationInfoResourcePath(pkg.codePath);
8618        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8619        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8620
8621        synchronized (mPackages) {
8622            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8623            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8624            if (realPkgName != null) {
8625                ensurePackageRenamed(pkg, renamedPkgName);
8626            }
8627            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8628            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8629            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8630            pkgAlreadyExists = pkgSetting != null;
8631            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8632            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8633            isSystemPkgUpdated = disabledPkgSetting != null;
8634
8635            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8636                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8637            }
8638
8639            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8640                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8641                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8642                    : null;
8643            if (DEBUG_PACKAGE_SCANNING
8644                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8645                    && sharedUserSetting != null) {
8646                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8647                        + " (uid=" + sharedUserSetting.userId + "):"
8648                        + " packages=" + sharedUserSetting.packages);
8649            }
8650
8651            if (scanSystemPartition) {
8652                // Potentially prune child packages. If the application on the /system
8653                // partition has been updated via OTA, but, is still disabled by a
8654                // version on /data, cycle through all of its children packages and
8655                // remove children that are no longer defined.
8656                if (isSystemPkgUpdated) {
8657                    final int scannedChildCount = (pkg.childPackages != null)
8658                            ? pkg.childPackages.size() : 0;
8659                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8660                            ? disabledPkgSetting.childPackageNames.size() : 0;
8661                    for (int i = 0; i < disabledChildCount; i++) {
8662                        String disabledChildPackageName =
8663                                disabledPkgSetting.childPackageNames.get(i);
8664                        boolean disabledPackageAvailable = false;
8665                        for (int j = 0; j < scannedChildCount; j++) {
8666                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8667                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8668                                disabledPackageAvailable = true;
8669                                break;
8670                            }
8671                        }
8672                        if (!disabledPackageAvailable) {
8673                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8674                        }
8675                    }
8676                    // we're updating the disabled package, so, scan it as the package setting
8677                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8678                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8679                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8680                            (pkg == mPlatformPackage), user);
8681                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8682                }
8683            }
8684        }
8685
8686        final boolean newPkgChangedPaths =
8687                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8688        final boolean newPkgVersionGreater =
8689                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8690        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8691                && newPkgChangedPaths && newPkgVersionGreater;
8692        if (isSystemPkgBetter) {
8693            // The version of the application on /system is greater than the version on
8694            // /data. Switch back to the application on /system.
8695            // It's safe to assume the application on /system will correctly scan. If not,
8696            // there won't be a working copy of the application.
8697            synchronized (mPackages) {
8698                // just remove the loaded entries from package lists
8699                mPackages.remove(pkgSetting.name);
8700            }
8701
8702            logCriticalInfo(Log.WARN,
8703                    "System package updated;"
8704                    + " name: " + pkgSetting.name
8705                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8706                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8707
8708            final InstallArgs args = createInstallArgsForExisting(
8709                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8710                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8711            args.cleanUpResourcesLI();
8712            synchronized (mPackages) {
8713                mSettings.enableSystemPackageLPw(pkgSetting.name);
8714            }
8715        }
8716
8717        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8718            // The version of the application on the /system partition is less than or
8719            // equal to the version on the /data partition. Throw an exception and use
8720            // the application already installed on the /data partition.
8721            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8722                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8723                    + " better than this " + pkg.getLongVersionCode());
8724        }
8725
8726        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8727        // force re-collecting certificate.
8728        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8729                disabledPkgSetting);
8730        // Full APK verification can be skipped during certificate collection, only if the file is
8731        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8732        // cases, only data in Signing Block is verified instead of the whole file.
8733        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8734                (forceCollect && canSkipFullPackageVerification(pkg));
8735        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8736
8737        boolean shouldHideSystemApp = false;
8738        // A new application appeared on /system, but, we already have a copy of
8739        // the application installed on /data.
8740        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8741                && !pkgSetting.isSystem()) {
8742
8743            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8744                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8745                logCriticalInfo(Log.WARN,
8746                        "System package signature mismatch;"
8747                        + " name: " + pkgSetting.name);
8748                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8749                        "scanPackageInternalLI")) {
8750                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8751                }
8752                pkgSetting = null;
8753            } else if (newPkgVersionGreater) {
8754                // The application on /system is newer than the application on /data.
8755                // Simply remove the application on /data [keeping application data]
8756                // and replace it with the version on /system.
8757                logCriticalInfo(Log.WARN,
8758                        "System package enabled;"
8759                        + " name: " + pkgSetting.name
8760                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8761                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8762                InstallArgs args = createInstallArgsForExisting(
8763                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8764                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8765                synchronized (mInstallLock) {
8766                    args.cleanUpResourcesLI();
8767                }
8768            } else {
8769                // The application on /system is older than the application on /data. Hide
8770                // the application on /system and the version on /data will be scanned later
8771                // and re-added like an update.
8772                shouldHideSystemApp = true;
8773                logCriticalInfo(Log.INFO,
8774                        "System package disabled;"
8775                        + " name: " + pkgSetting.name
8776                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8777                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8778            }
8779        }
8780
8781        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8782                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8783
8784        if (shouldHideSystemApp) {
8785            synchronized (mPackages) {
8786                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8787            }
8788        }
8789        return scannedPkg;
8790    }
8791
8792    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8793        // Derive the new package synthetic package name
8794        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8795                + pkg.staticSharedLibVersion);
8796    }
8797
8798    private static String fixProcessName(String defProcessName,
8799            String processName) {
8800        if (processName == null) {
8801            return defProcessName;
8802        }
8803        return processName;
8804    }
8805
8806    /**
8807     * Enforces that only the system UID or root's UID can call a method exposed
8808     * via Binder.
8809     *
8810     * @param message used as message if SecurityException is thrown
8811     * @throws SecurityException if the caller is not system or root
8812     */
8813    private static final void enforceSystemOrRoot(String message) {
8814        final int uid = Binder.getCallingUid();
8815        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8816            throw new SecurityException(message);
8817        }
8818    }
8819
8820    @Override
8821    public void performFstrimIfNeeded() {
8822        enforceSystemOrRoot("Only the system can request fstrim");
8823
8824        // Before everything else, see whether we need to fstrim.
8825        try {
8826            IStorageManager sm = PackageHelper.getStorageManager();
8827            if (sm != null) {
8828                boolean doTrim = false;
8829                final long interval = android.provider.Settings.Global.getLong(
8830                        mContext.getContentResolver(),
8831                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8832                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8833                if (interval > 0) {
8834                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8835                    if (timeSinceLast > interval) {
8836                        doTrim = true;
8837                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8838                                + "; running immediately");
8839                    }
8840                }
8841                if (doTrim) {
8842                    final boolean dexOptDialogShown;
8843                    synchronized (mPackages) {
8844                        dexOptDialogShown = mDexOptDialogShown;
8845                    }
8846                    if (!isFirstBoot() && dexOptDialogShown) {
8847                        try {
8848                            ActivityManager.getService().showBootMessage(
8849                                    mContext.getResources().getString(
8850                                            R.string.android_upgrading_fstrim), true);
8851                        } catch (RemoteException e) {
8852                        }
8853                    }
8854                    sm.runMaintenance();
8855                }
8856            } else {
8857                Slog.e(TAG, "storageManager service unavailable!");
8858            }
8859        } catch (RemoteException e) {
8860            // Can't happen; StorageManagerService is local
8861        }
8862    }
8863
8864    @Override
8865    public void updatePackagesIfNeeded() {
8866        enforceSystemOrRoot("Only the system can request package update");
8867
8868        // We need to re-extract after an OTA.
8869        boolean causeUpgrade = isUpgrade();
8870
8871        // First boot or factory reset.
8872        // Note: we also handle devices that are upgrading to N right now as if it is their
8873        //       first boot, as they do not have profile data.
8874        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8875
8876        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8877        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8878
8879        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8880            return;
8881        }
8882
8883        List<PackageParser.Package> pkgs;
8884        synchronized (mPackages) {
8885            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8886        }
8887
8888        final long startTime = System.nanoTime();
8889        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8890                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8891                    false /* bootComplete */);
8892
8893        final int elapsedTimeSeconds =
8894                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8895
8896        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8897        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8898        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8899        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8900        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8901    }
8902
8903    /*
8904     * Return the prebuilt profile path given a package base code path.
8905     */
8906    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8907        return pkg.baseCodePath + ".prof";
8908    }
8909
8910    /**
8911     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8912     * containing statistics about the invocation. The array consists of three elements,
8913     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8914     * and {@code numberOfPackagesFailed}.
8915     */
8916    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8917            final int compilationReason, boolean bootComplete) {
8918
8919        int numberOfPackagesVisited = 0;
8920        int numberOfPackagesOptimized = 0;
8921        int numberOfPackagesSkipped = 0;
8922        int numberOfPackagesFailed = 0;
8923        final int numberOfPackagesToDexopt = pkgs.size();
8924
8925        for (PackageParser.Package pkg : pkgs) {
8926            numberOfPackagesVisited++;
8927
8928            boolean useProfileForDexopt = false;
8929
8930            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8931                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8932                // that are already compiled.
8933                File profileFile = new File(getPrebuildProfilePath(pkg));
8934                // Copy profile if it exists.
8935                if (profileFile.exists()) {
8936                    try {
8937                        // We could also do this lazily before calling dexopt in
8938                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8939                        // is that we don't have a good way to say "do this only once".
8940                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8941                                pkg.applicationInfo.uid, pkg.packageName,
8942                                ArtManager.getProfileName(null))) {
8943                            Log.e(TAG, "Installer failed to copy system profile!");
8944                        } else {
8945                            // Disabled as this causes speed-profile compilation during first boot
8946                            // even if things are already compiled.
8947                            // useProfileForDexopt = true;
8948                        }
8949                    } catch (Exception e) {
8950                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8951                                e);
8952                    }
8953                } else {
8954                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8955                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8956                    // minimize the number off apps being speed-profile compiled during first boot.
8957                    // The other paths will not change the filter.
8958                    if (disabledPs != null && disabledPs.pkg.isStub) {
8959                        // The package is the stub one, remove the stub suffix to get the normal
8960                        // package and APK names.
8961                        String systemProfilePath =
8962                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8963                        profileFile = new File(systemProfilePath);
8964                        // If we have a profile for a compressed APK, copy it to the reference
8965                        // location.
8966                        // Note that copying the profile here will cause it to override the
8967                        // reference profile every OTA even though the existing reference profile
8968                        // may have more data. We can't copy during decompression since the
8969                        // directories are not set up at that point.
8970                        if (profileFile.exists()) {
8971                            try {
8972                                // We could also do this lazily before calling dexopt in
8973                                // PackageDexOptimizer to prevent this happening on first boot. The
8974                                // issue is that we don't have a good way to say "do this only
8975                                // once".
8976                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8977                                        pkg.applicationInfo.uid, pkg.packageName,
8978                                        ArtManager.getProfileName(null))) {
8979                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8980                                } else {
8981                                    useProfileForDexopt = true;
8982                                }
8983                            } catch (Exception e) {
8984                                Log.e(TAG, "Failed to copy profile " +
8985                                        profileFile.getAbsolutePath() + " ", e);
8986                            }
8987                        }
8988                    }
8989                }
8990            }
8991
8992            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8993                if (DEBUG_DEXOPT) {
8994                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8995                }
8996                numberOfPackagesSkipped++;
8997                continue;
8998            }
8999
9000            if (DEBUG_DEXOPT) {
9001                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9002                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9003            }
9004
9005            if (showDialog) {
9006                try {
9007                    ActivityManager.getService().showBootMessage(
9008                            mContext.getResources().getString(R.string.android_upgrading_apk,
9009                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9010                } catch (RemoteException e) {
9011                }
9012                synchronized (mPackages) {
9013                    mDexOptDialogShown = true;
9014                }
9015            }
9016
9017            int pkgCompilationReason = compilationReason;
9018            if (useProfileForDexopt) {
9019                // Use background dexopt mode to try and use the profile. Note that this does not
9020                // guarantee usage of the profile.
9021                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9022            }
9023
9024            // checkProfiles is false to avoid merging profiles during boot which
9025            // might interfere with background compilation (b/28612421).
9026            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9027            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9028            // trade-off worth doing to save boot time work.
9029            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9030            if (compilationReason == REASON_FIRST_BOOT) {
9031                // TODO: This doesn't cover the upgrade case, we should check for this too.
9032                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9033            }
9034            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9035                    pkg.packageName,
9036                    pkgCompilationReason,
9037                    dexoptFlags));
9038
9039            switch (primaryDexOptStaus) {
9040                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9041                    numberOfPackagesOptimized++;
9042                    break;
9043                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9044                    numberOfPackagesSkipped++;
9045                    break;
9046                case PackageDexOptimizer.DEX_OPT_FAILED:
9047                    numberOfPackagesFailed++;
9048                    break;
9049                default:
9050                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9051                    break;
9052            }
9053        }
9054
9055        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9056                numberOfPackagesFailed };
9057    }
9058
9059    @Override
9060    public void notifyPackageUse(String packageName, int reason) {
9061        synchronized (mPackages) {
9062            final int callingUid = Binder.getCallingUid();
9063            final int callingUserId = UserHandle.getUserId(callingUid);
9064            if (getInstantAppPackageName(callingUid) != null) {
9065                if (!isCallerSameApp(packageName, callingUid)) {
9066                    return;
9067                }
9068            } else {
9069                if (isInstantApp(packageName, callingUserId)) {
9070                    return;
9071                }
9072            }
9073            notifyPackageUseLocked(packageName, reason);
9074        }
9075    }
9076
9077    @GuardedBy("mPackages")
9078    private void notifyPackageUseLocked(String packageName, int reason) {
9079        final PackageParser.Package p = mPackages.get(packageName);
9080        if (p == null) {
9081            return;
9082        }
9083        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9084    }
9085
9086    @Override
9087    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9088            List<String> classPaths, String loaderIsa) {
9089        int userId = UserHandle.getCallingUserId();
9090        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9091        if (ai == null) {
9092            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9093                + loadingPackageName + ", user=" + userId);
9094            return;
9095        }
9096        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9097    }
9098
9099    @Override
9100    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9101            IDexModuleRegisterCallback callback) {
9102        int userId = UserHandle.getCallingUserId();
9103        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9104        DexManager.RegisterDexModuleResult result;
9105        if (ai == null) {
9106            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9107                     " calling user. package=" + packageName + ", user=" + userId);
9108            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9109        } else {
9110            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9111        }
9112
9113        if (callback != null) {
9114            mHandler.post(() -> {
9115                try {
9116                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9117                } catch (RemoteException e) {
9118                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9119                }
9120            });
9121        }
9122    }
9123
9124    /**
9125     * Ask the package manager to perform a dex-opt with the given compiler filter.
9126     *
9127     * Note: exposed only for the shell command to allow moving packages explicitly to a
9128     *       definite state.
9129     */
9130    @Override
9131    public boolean performDexOptMode(String packageName,
9132            boolean checkProfiles, String targetCompilerFilter, boolean force,
9133            boolean bootComplete, String splitName) {
9134        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9135                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9136                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9137        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9138                targetCompilerFilter, splitName, flags));
9139    }
9140
9141    /**
9142     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9143     * secondary dex files belonging to the given package.
9144     *
9145     * Note: exposed only for the shell command to allow moving packages explicitly to a
9146     *       definite state.
9147     */
9148    @Override
9149    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9150            boolean force) {
9151        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9152                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9153                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9154                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9155        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9156    }
9157
9158    /*package*/ boolean performDexOpt(DexoptOptions options) {
9159        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9160            return false;
9161        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9162            return false;
9163        }
9164
9165        if (options.isDexoptOnlySecondaryDex()) {
9166            return mDexManager.dexoptSecondaryDex(options);
9167        } else {
9168            int dexoptStatus = performDexOptWithStatus(options);
9169            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9170        }
9171    }
9172
9173    /**
9174     * Perform dexopt on the given package and return one of following result:
9175     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9176     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9177     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9178     */
9179    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9180        return performDexOptTraced(options);
9181    }
9182
9183    private int performDexOptTraced(DexoptOptions options) {
9184        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9185        try {
9186            return performDexOptInternal(options);
9187        } finally {
9188            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9189        }
9190    }
9191
9192    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9193    // if the package can now be considered up to date for the given filter.
9194    private int performDexOptInternal(DexoptOptions options) {
9195        PackageParser.Package p;
9196        synchronized (mPackages) {
9197            p = mPackages.get(options.getPackageName());
9198            if (p == null) {
9199                // Package could not be found. Report failure.
9200                return PackageDexOptimizer.DEX_OPT_FAILED;
9201            }
9202            mPackageUsage.maybeWriteAsync(mPackages);
9203            mCompilerStats.maybeWriteAsync();
9204        }
9205        long callingId = Binder.clearCallingIdentity();
9206        try {
9207            synchronized (mInstallLock) {
9208                return performDexOptInternalWithDependenciesLI(p, options);
9209            }
9210        } finally {
9211            Binder.restoreCallingIdentity(callingId);
9212        }
9213    }
9214
9215    public ArraySet<String> getOptimizablePackages() {
9216        ArraySet<String> pkgs = new ArraySet<String>();
9217        synchronized (mPackages) {
9218            for (PackageParser.Package p : mPackages.values()) {
9219                if (PackageDexOptimizer.canOptimizePackage(p)) {
9220                    pkgs.add(p.packageName);
9221                }
9222            }
9223        }
9224        return pkgs;
9225    }
9226
9227    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9228            DexoptOptions options) {
9229        // Select the dex optimizer based on the force parameter.
9230        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9231        //       allocate an object here.
9232        PackageDexOptimizer pdo = options.isForce()
9233                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9234                : mPackageDexOptimizer;
9235
9236        // Dexopt all dependencies first. Note: we ignore the return value and march on
9237        // on errors.
9238        // Note that we are going to call performDexOpt on those libraries as many times as
9239        // they are referenced in packages. When we do a batch of performDexOpt (for example
9240        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9241        // and the first package that uses the library will dexopt it. The
9242        // others will see that the compiled code for the library is up to date.
9243        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9244        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9245        if (!deps.isEmpty()) {
9246            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9247                    options.getCompilationReason(), options.getCompilerFilter(),
9248                    options.getSplitName(),
9249                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9250            for (PackageParser.Package depPackage : deps) {
9251                // TODO: Analyze and investigate if we (should) profile libraries.
9252                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9253                        getOrCreateCompilerPackageStats(depPackage),
9254                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9255            }
9256        }
9257        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9258                getOrCreateCompilerPackageStats(p),
9259                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9260    }
9261
9262    /**
9263     * Reconcile the information we have about the secondary dex files belonging to
9264     * {@code packagName} and the actual dex files. For all dex files that were
9265     * deleted, update the internal records and delete the generated oat files.
9266     */
9267    @Override
9268    public void reconcileSecondaryDexFiles(String packageName) {
9269        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9270            return;
9271        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9272            return;
9273        }
9274        mDexManager.reconcileSecondaryDexFiles(packageName);
9275    }
9276
9277    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9278    // a reference there.
9279    /*package*/ DexManager getDexManager() {
9280        return mDexManager;
9281    }
9282
9283    /**
9284     * Execute the background dexopt job immediately.
9285     */
9286    @Override
9287    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9288        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9289            return false;
9290        }
9291        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9292    }
9293
9294    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9295        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9296                || p.usesStaticLibraries != null) {
9297            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9298            Set<String> collectedNames = new HashSet<>();
9299            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9300
9301            retValue.remove(p);
9302
9303            return retValue;
9304        } else {
9305            return Collections.emptyList();
9306        }
9307    }
9308
9309    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9310            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9311        if (!collectedNames.contains(p.packageName)) {
9312            collectedNames.add(p.packageName);
9313            collected.add(p);
9314
9315            if (p.usesLibraries != null) {
9316                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9317                        null, collected, collectedNames);
9318            }
9319            if (p.usesOptionalLibraries != null) {
9320                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9321                        null, collected, collectedNames);
9322            }
9323            if (p.usesStaticLibraries != null) {
9324                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9325                        p.usesStaticLibrariesVersions, collected, collectedNames);
9326            }
9327        }
9328    }
9329
9330    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9331            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9332        final int libNameCount = libs.size();
9333        for (int i = 0; i < libNameCount; i++) {
9334            String libName = libs.get(i);
9335            long version = (versions != null && versions.length == libNameCount)
9336                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9337            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9338            if (libPkg != null) {
9339                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9340            }
9341        }
9342    }
9343
9344    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9345        synchronized (mPackages) {
9346            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9347            if (libEntry != null) {
9348                return mPackages.get(libEntry.apk);
9349            }
9350            return null;
9351        }
9352    }
9353
9354    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9355        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9356        if (versionedLib == null) {
9357            return null;
9358        }
9359        return versionedLib.get(version);
9360    }
9361
9362    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9363        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9364                pkg.staticSharedLibName);
9365        if (versionedLib == null) {
9366            return null;
9367        }
9368        long previousLibVersion = -1;
9369        final int versionCount = versionedLib.size();
9370        for (int i = 0; i < versionCount; i++) {
9371            final long libVersion = versionedLib.keyAt(i);
9372            if (libVersion < pkg.staticSharedLibVersion) {
9373                previousLibVersion = Math.max(previousLibVersion, libVersion);
9374            }
9375        }
9376        if (previousLibVersion >= 0) {
9377            return versionedLib.get(previousLibVersion);
9378        }
9379        return null;
9380    }
9381
9382    public void shutdown() {
9383        mPackageUsage.writeNow(mPackages);
9384        mCompilerStats.writeNow();
9385        mDexManager.writePackageDexUsageNow();
9386    }
9387
9388    @Override
9389    public void dumpProfiles(String packageName) {
9390        PackageParser.Package pkg;
9391        synchronized (mPackages) {
9392            pkg = mPackages.get(packageName);
9393            if (pkg == null) {
9394                throw new IllegalArgumentException("Unknown package: " + packageName);
9395            }
9396        }
9397        /* Only the shell, root, or the app user should be able to dump profiles. */
9398        int callingUid = Binder.getCallingUid();
9399        if (callingUid != Process.SHELL_UID &&
9400            callingUid != Process.ROOT_UID &&
9401            callingUid != pkg.applicationInfo.uid) {
9402            throw new SecurityException("dumpProfiles");
9403        }
9404
9405        synchronized (mInstallLock) {
9406            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9407            mArtManagerService.dumpProfiles(pkg);
9408            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9409        }
9410    }
9411
9412    @Override
9413    public void forceDexOpt(String packageName) {
9414        enforceSystemOrRoot("forceDexOpt");
9415
9416        PackageParser.Package pkg;
9417        synchronized (mPackages) {
9418            pkg = mPackages.get(packageName);
9419            if (pkg == null) {
9420                throw new IllegalArgumentException("Unknown package: " + packageName);
9421            }
9422        }
9423
9424        synchronized (mInstallLock) {
9425            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9426
9427            // Whoever is calling forceDexOpt wants a compiled package.
9428            // Don't use profiles since that may cause compilation to be skipped.
9429            final int res = performDexOptInternalWithDependenciesLI(
9430                    pkg,
9431                    new DexoptOptions(packageName,
9432                            getDefaultCompilerFilter(),
9433                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9434
9435            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9436            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9437                throw new IllegalStateException("Failed to dexopt: " + res);
9438            }
9439        }
9440    }
9441
9442    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9443        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9444            Slog.w(TAG, "Unable to update from " + oldPkg.name
9445                    + " to " + newPkg.packageName
9446                    + ": old package not in system partition");
9447            return false;
9448        } else if (mPackages.get(oldPkg.name) != null) {
9449            Slog.w(TAG, "Unable to update from " + oldPkg.name
9450                    + " to " + newPkg.packageName
9451                    + ": old package still exists");
9452            return false;
9453        }
9454        return true;
9455    }
9456
9457    void removeCodePathLI(File codePath) {
9458        if (codePath.isDirectory()) {
9459            try {
9460                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9461            } catch (InstallerException e) {
9462                Slog.w(TAG, "Failed to remove code path", e);
9463            }
9464        } else {
9465            codePath.delete();
9466        }
9467    }
9468
9469    private int[] resolveUserIds(int userId) {
9470        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9471    }
9472
9473    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9474        if (pkg == null) {
9475            Slog.wtf(TAG, "Package was null!", new Throwable());
9476            return;
9477        }
9478        clearAppDataLeafLIF(pkg, userId, flags);
9479        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9480        for (int i = 0; i < childCount; i++) {
9481            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9482        }
9483
9484        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9485    }
9486
9487    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9488        final PackageSetting ps;
9489        synchronized (mPackages) {
9490            ps = mSettings.mPackages.get(pkg.packageName);
9491        }
9492        for (int realUserId : resolveUserIds(userId)) {
9493            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9494            try {
9495                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9496                        ceDataInode);
9497            } catch (InstallerException e) {
9498                Slog.w(TAG, String.valueOf(e));
9499            }
9500        }
9501    }
9502
9503    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9504        if (pkg == null) {
9505            Slog.wtf(TAG, "Package was null!", new Throwable());
9506            return;
9507        }
9508        destroyAppDataLeafLIF(pkg, userId, flags);
9509        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9510        for (int i = 0; i < childCount; i++) {
9511            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9512        }
9513    }
9514
9515    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9516        final PackageSetting ps;
9517        synchronized (mPackages) {
9518            ps = mSettings.mPackages.get(pkg.packageName);
9519        }
9520        for (int realUserId : resolveUserIds(userId)) {
9521            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9522            try {
9523                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9524                        ceDataInode);
9525            } catch (InstallerException e) {
9526                Slog.w(TAG, String.valueOf(e));
9527            }
9528            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9529        }
9530    }
9531
9532    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9533        if (pkg == null) {
9534            Slog.wtf(TAG, "Package was null!", new Throwable());
9535            return;
9536        }
9537        destroyAppProfilesLeafLIF(pkg);
9538        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9539        for (int i = 0; i < childCount; i++) {
9540            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9541        }
9542    }
9543
9544    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9545        try {
9546            mInstaller.destroyAppProfiles(pkg.packageName);
9547        } catch (InstallerException e) {
9548            Slog.w(TAG, String.valueOf(e));
9549        }
9550    }
9551
9552    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9553        if (pkg == null) {
9554            Slog.wtf(TAG, "Package was null!", new Throwable());
9555            return;
9556        }
9557        mArtManagerService.clearAppProfiles(pkg);
9558        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9559        for (int i = 0; i < childCount; i++) {
9560            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9561        }
9562    }
9563
9564    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9565            long lastUpdateTime) {
9566        // Set parent install/update time
9567        PackageSetting ps = (PackageSetting) pkg.mExtras;
9568        if (ps != null) {
9569            ps.firstInstallTime = firstInstallTime;
9570            ps.lastUpdateTime = lastUpdateTime;
9571        }
9572        // Set children install/update time
9573        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9574        for (int i = 0; i < childCount; i++) {
9575            PackageParser.Package childPkg = pkg.childPackages.get(i);
9576            ps = (PackageSetting) childPkg.mExtras;
9577            if (ps != null) {
9578                ps.firstInstallTime = firstInstallTime;
9579                ps.lastUpdateTime = lastUpdateTime;
9580            }
9581        }
9582    }
9583
9584    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9585            SharedLibraryEntry file,
9586            PackageParser.Package changingLib) {
9587        if (file.path != null) {
9588            usesLibraryFiles.add(file.path);
9589            return;
9590        }
9591        PackageParser.Package p = mPackages.get(file.apk);
9592        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9593            // If we are doing this while in the middle of updating a library apk,
9594            // then we need to make sure to use that new apk for determining the
9595            // dependencies here.  (We haven't yet finished committing the new apk
9596            // to the package manager state.)
9597            if (p == null || p.packageName.equals(changingLib.packageName)) {
9598                p = changingLib;
9599            }
9600        }
9601        if (p != null) {
9602            usesLibraryFiles.addAll(p.getAllCodePaths());
9603            if (p.usesLibraryFiles != null) {
9604                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9605            }
9606        }
9607    }
9608
9609    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9610            PackageParser.Package changingLib) throws PackageManagerException {
9611        if (pkg == null) {
9612            return;
9613        }
9614        // The collection used here must maintain the order of addition (so
9615        // that libraries are searched in the correct order) and must have no
9616        // duplicates.
9617        Set<String> usesLibraryFiles = null;
9618        if (pkg.usesLibraries != null) {
9619            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9620                    null, null, pkg.packageName, changingLib, true,
9621                    pkg.applicationInfo.targetSdkVersion, null);
9622        }
9623        if (pkg.usesStaticLibraries != null) {
9624            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9625                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9626                    pkg.packageName, changingLib, true,
9627                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9628        }
9629        if (pkg.usesOptionalLibraries != null) {
9630            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9631                    null, null, pkg.packageName, changingLib, false,
9632                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9633        }
9634        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9635            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9636        } else {
9637            pkg.usesLibraryFiles = null;
9638        }
9639    }
9640
9641    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9642            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9643            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9644            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9645            throws PackageManagerException {
9646        final int libCount = requestedLibraries.size();
9647        for (int i = 0; i < libCount; i++) {
9648            final String libName = requestedLibraries.get(i);
9649            final long libVersion = requiredVersions != null ? requiredVersions[i]
9650                    : SharedLibraryInfo.VERSION_UNDEFINED;
9651            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9652            if (libEntry == null) {
9653                if (required) {
9654                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9655                            "Package " + packageName + " requires unavailable shared library "
9656                                    + libName + "; failing!");
9657                } else if (DEBUG_SHARED_LIBRARIES) {
9658                    Slog.i(TAG, "Package " + packageName
9659                            + " desires unavailable shared library "
9660                            + libName + "; ignoring!");
9661                }
9662            } else {
9663                if (requiredVersions != null && requiredCertDigests != null) {
9664                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9665                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9666                            "Package " + packageName + " requires unavailable static shared"
9667                                    + " library " + libName + " version "
9668                                    + libEntry.info.getLongVersion() + "; failing!");
9669                    }
9670
9671                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9672                    if (libPkg == null) {
9673                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9674                                "Package " + packageName + " requires unavailable static shared"
9675                                        + " library; failing!");
9676                    }
9677
9678                    final String[] expectedCertDigests = requiredCertDigests[i];
9679
9680
9681                    if (expectedCertDigests.length > 1) {
9682
9683                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9684                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9685                                ? PackageUtils.computeSignaturesSha256Digests(
9686                                libPkg.mSigningDetails.signatures)
9687                                : PackageUtils.computeSignaturesSha256Digests(
9688                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9689
9690                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9691                        // target O we don't parse the "additional-certificate" tags similarly
9692                        // how we only consider all certs only for apps targeting O (see above).
9693                        // Therefore, the size check is safe to make.
9694                        if (expectedCertDigests.length != libCertDigests.length) {
9695                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9696                                    "Package " + packageName + " requires differently signed" +
9697                                            " static shared library; failing!");
9698                        }
9699
9700                        // Use a predictable order as signature order may vary
9701                        Arrays.sort(libCertDigests);
9702                        Arrays.sort(expectedCertDigests);
9703
9704                        final int certCount = libCertDigests.length;
9705                        for (int j = 0; j < certCount; j++) {
9706                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9707                                throw new PackageManagerException(
9708                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9709                                        "Package " + packageName + " requires differently signed" +
9710                                                " static shared library; failing!");
9711                            }
9712                        }
9713                    } else {
9714
9715                        // lib signing cert could have rotated beyond the one expected, check to see
9716                        // if the new one has been blessed by the old
9717                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9718                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9719                            throw new PackageManagerException(
9720                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9721                                    "Package " + packageName + " requires differently signed" +
9722                                            " static shared library; failing!");
9723                        }
9724                    }
9725                }
9726
9727                if (outUsedLibraries == null) {
9728                    // Use LinkedHashSet to preserve the order of files added to
9729                    // usesLibraryFiles while eliminating duplicates.
9730                    outUsedLibraries = new LinkedHashSet<>();
9731                }
9732                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9733            }
9734        }
9735        return outUsedLibraries;
9736    }
9737
9738    private static boolean hasString(List<String> list, List<String> which) {
9739        if (list == null) {
9740            return false;
9741        }
9742        for (int i=list.size()-1; i>=0; i--) {
9743            for (int j=which.size()-1; j>=0; j--) {
9744                if (which.get(j).equals(list.get(i))) {
9745                    return true;
9746                }
9747            }
9748        }
9749        return false;
9750    }
9751
9752    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9753            PackageParser.Package changingPkg) {
9754        ArrayList<PackageParser.Package> res = null;
9755        for (PackageParser.Package pkg : mPackages.values()) {
9756            if (changingPkg != null
9757                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9758                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9759                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9760                            changingPkg.staticSharedLibName)) {
9761                return null;
9762            }
9763            if (res == null) {
9764                res = new ArrayList<>();
9765            }
9766            res.add(pkg);
9767            try {
9768                updateSharedLibrariesLPr(pkg, changingPkg);
9769            } catch (PackageManagerException e) {
9770                // If a system app update or an app and a required lib missing we
9771                // delete the package and for updated system apps keep the data as
9772                // it is better for the user to reinstall than to be in an limbo
9773                // state. Also libs disappearing under an app should never happen
9774                // - just in case.
9775                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9776                    final int flags = pkg.isUpdatedSystemApp()
9777                            ? PackageManager.DELETE_KEEP_DATA : 0;
9778                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9779                            flags , null, true, null);
9780                }
9781                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9782            }
9783        }
9784        return res;
9785    }
9786
9787    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9788            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9789            @Nullable UserHandle user) throws PackageManagerException {
9790        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9791        // If the package has children and this is the first dive in the function
9792        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9793        // whether all packages (parent and children) would be successfully scanned
9794        // before the actual scan since scanning mutates internal state and we want
9795        // to atomically install the package and its children.
9796        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9797            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9798                scanFlags |= SCAN_CHECK_ONLY;
9799            }
9800        } else {
9801            scanFlags &= ~SCAN_CHECK_ONLY;
9802        }
9803
9804        final PackageParser.Package scannedPkg;
9805        try {
9806            // Scan the parent
9807            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9808            // Scan the children
9809            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9810            for (int i = 0; i < childCount; i++) {
9811                PackageParser.Package childPkg = pkg.childPackages.get(i);
9812                scanPackageNewLI(childPkg, parseFlags,
9813                        scanFlags, currentTime, user);
9814            }
9815        } finally {
9816            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9817        }
9818
9819        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9820            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9821        }
9822
9823        return scannedPkg;
9824    }
9825
9826    /** The result of a package scan. */
9827    private static class ScanResult {
9828        /** Whether or not the package scan was successful */
9829        public final boolean success;
9830        /**
9831         * The final package settings. This may be the same object passed in
9832         * the {@link ScanRequest}, but, with modified values.
9833         */
9834        @Nullable public final PackageSetting pkgSetting;
9835        /** ABI code paths that have changed in the package scan */
9836        @Nullable public final List<String> changedAbiCodePath;
9837        public ScanResult(
9838                boolean success,
9839                @Nullable PackageSetting pkgSetting,
9840                @Nullable List<String> changedAbiCodePath) {
9841            this.success = success;
9842            this.pkgSetting = pkgSetting;
9843            this.changedAbiCodePath = changedAbiCodePath;
9844        }
9845    }
9846
9847    /** A package to be scanned */
9848    private static class ScanRequest {
9849        /** The parsed package */
9850        @NonNull public final PackageParser.Package pkg;
9851        /** Shared user settings, if the package has a shared user */
9852        @Nullable public final SharedUserSetting sharedUserSetting;
9853        /**
9854         * Package settings of the currently installed version.
9855         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9856         * during scan.
9857         */
9858        @Nullable public final PackageSetting pkgSetting;
9859        /** A copy of the settings for the currently installed version */
9860        @Nullable public final PackageSetting oldPkgSetting;
9861        /** Package settings for the disabled version on the /system partition */
9862        @Nullable public final PackageSetting disabledPkgSetting;
9863        /** Package settings for the installed version under its original package name */
9864        @Nullable public final PackageSetting originalPkgSetting;
9865        /** The real package name of a renamed application */
9866        @Nullable public final String realPkgName;
9867        public final @ParseFlags int parseFlags;
9868        public final @ScanFlags int scanFlags;
9869        /** The user for which the package is being scanned */
9870        @Nullable public final UserHandle user;
9871        /** Whether or not the platform package is being scanned */
9872        public final boolean isPlatformPackage;
9873        public ScanRequest(
9874                @NonNull PackageParser.Package pkg,
9875                @Nullable SharedUserSetting sharedUserSetting,
9876                @Nullable PackageSetting pkgSetting,
9877                @Nullable PackageSetting disabledPkgSetting,
9878                @Nullable PackageSetting originalPkgSetting,
9879                @Nullable String realPkgName,
9880                @ParseFlags int parseFlags,
9881                @ScanFlags int scanFlags,
9882                boolean isPlatformPackage,
9883                @Nullable UserHandle user) {
9884            this.pkg = pkg;
9885            this.pkgSetting = pkgSetting;
9886            this.sharedUserSetting = sharedUserSetting;
9887            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9888            this.disabledPkgSetting = disabledPkgSetting;
9889            this.originalPkgSetting = originalPkgSetting;
9890            this.realPkgName = realPkgName;
9891            this.parseFlags = parseFlags;
9892            this.scanFlags = scanFlags;
9893            this.isPlatformPackage = isPlatformPackage;
9894            this.user = user;
9895        }
9896    }
9897
9898    /**
9899     * Returns the actual scan flags depending upon the state of the other settings.
9900     * <p>Updated system applications will not have the following flags set
9901     * by default and need to be adjusted after the fact:
9902     * <ul>
9903     * <li>{@link #SCAN_AS_SYSTEM}</li>
9904     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9905     * <li>{@link #SCAN_AS_OEM}</li>
9906     * <li>{@link #SCAN_AS_VENDOR}</li>
9907     * <li>{@link #SCAN_AS_PRODUCT}</li>
9908     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9909     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9910     * </ul>
9911     */
9912    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9913            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9914            PackageParser.Package pkg) {
9915        if (disabledPkgSetting != null) {
9916            // updated system application, must at least have SCAN_AS_SYSTEM
9917            scanFlags |= SCAN_AS_SYSTEM;
9918            if ((disabledPkgSetting.pkgPrivateFlags
9919                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9920                scanFlags |= SCAN_AS_PRIVILEGED;
9921            }
9922            if ((disabledPkgSetting.pkgPrivateFlags
9923                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9924                scanFlags |= SCAN_AS_OEM;
9925            }
9926            if ((disabledPkgSetting.pkgPrivateFlags
9927                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9928                scanFlags |= SCAN_AS_VENDOR;
9929            }
9930            if ((disabledPkgSetting.pkgPrivateFlags
9931                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9932                scanFlags |= SCAN_AS_PRODUCT;
9933            }
9934        }
9935        if (pkgSetting != null) {
9936            final int userId = ((user == null) ? 0 : user.getIdentifier());
9937            if (pkgSetting.getInstantApp(userId)) {
9938                scanFlags |= SCAN_AS_INSTANT_APP;
9939            }
9940            if (pkgSetting.getVirtulalPreload(userId)) {
9941                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9942            }
9943        }
9944
9945        // Scan as privileged apps that share a user with a priv-app.
9946        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9947                && (pkg.mSharedUserId != null)) {
9948            SharedUserSetting sharedUserSetting = null;
9949            try {
9950                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9951            } catch (PackageManagerException ignore) {}
9952            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9953                // Exempt SharedUsers signed with the platform key.
9954                // TODO(b/72378145) Fix this exemption. Force signature apps
9955                // to whitelist their privileged permissions just like other
9956                // priv-apps.
9957                synchronized (mPackages) {
9958                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9959                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9960                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9961                        scanFlags |= SCAN_AS_PRIVILEGED;
9962                    }
9963                }
9964            }
9965        }
9966
9967        return scanFlags;
9968    }
9969
9970    @GuardedBy("mInstallLock")
9971    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9972            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9973            @Nullable UserHandle user) throws PackageManagerException {
9974
9975        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9976        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9977        if (realPkgName != null) {
9978            ensurePackageRenamed(pkg, renamedPkgName);
9979        }
9980        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9981        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9982        final PackageSetting disabledPkgSetting =
9983                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9984
9985        if (mTransferedPackages.contains(pkg.packageName)) {
9986            Slog.w(TAG, "Package " + pkg.packageName
9987                    + " was transferred to another, but its .apk remains");
9988        }
9989
9990        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
9991        synchronized (mPackages) {
9992            applyPolicy(pkg, parseFlags, scanFlags);
9993            assertPackageIsValid(pkg, parseFlags, scanFlags);
9994
9995            SharedUserSetting sharedUserSetting = null;
9996            if (pkg.mSharedUserId != null) {
9997                // SIDE EFFECTS; may potentially allocate a new shared user
9998                sharedUserSetting = mSettings.getSharedUserLPw(
9999                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10000                if (DEBUG_PACKAGE_SCANNING) {
10001                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10002                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10003                                + " (uid=" + sharedUserSetting.userId + "):"
10004                                + " packages=" + sharedUserSetting.packages);
10005                }
10006            }
10007
10008            boolean scanSucceeded = false;
10009            try {
10010                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
10011                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
10012                        (pkg == mPlatformPackage), user);
10013                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10014                if (result.success) {
10015                    commitScanResultsLocked(request, result);
10016                }
10017                scanSucceeded = true;
10018            } finally {
10019                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10020                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10021                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10022                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10023                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10024                  }
10025            }
10026        }
10027        return pkg;
10028    }
10029
10030    /**
10031     * Commits the package scan and modifies system state.
10032     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10033     * of committing the package, leaving the system in an inconsistent state.
10034     * This needs to be fixed so, once we get to this point, no errors are
10035     * possible and the system is not left in an inconsistent state.
10036     */
10037    @GuardedBy("mPackages")
10038    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10039            throws PackageManagerException {
10040        final PackageParser.Package pkg = request.pkg;
10041        final @ParseFlags int parseFlags = request.parseFlags;
10042        final @ScanFlags int scanFlags = request.scanFlags;
10043        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10044        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10045        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10046        final UserHandle user = request.user;
10047        final String realPkgName = request.realPkgName;
10048        final PackageSetting pkgSetting = result.pkgSetting;
10049        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10050        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10051
10052        if (newPkgSettingCreated) {
10053            if (originalPkgSetting != null) {
10054                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10055            }
10056            // THROWS: when we can't allocate a user id. add call to check if there's
10057            // enough space to ensure we won't throw; otherwise, don't modify state
10058            mSettings.addUserToSettingLPw(pkgSetting);
10059
10060            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10061                mTransferedPackages.add(originalPkgSetting.name);
10062            }
10063        }
10064        // TODO(toddke): Consider a method specifically for modifying the Package object
10065        // post scan; or, moving this stuff out of the Package object since it has nothing
10066        // to do with the package on disk.
10067        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10068        // for creating the application ID. If we did this earlier, we would be saving the
10069        // correct ID.
10070        pkg.applicationInfo.uid = pkgSetting.appId;
10071
10072        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10073
10074        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10075            mTransferedPackages.add(pkg.packageName);
10076        }
10077
10078        // THROWS: when requested libraries that can't be found. it only changes
10079        // the state of the passed in pkg object, so, move to the top of the method
10080        // and allow it to abort
10081        if ((scanFlags & SCAN_BOOTING) == 0
10082                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10083            // Check all shared libraries and map to their actual file path.
10084            // We only do this here for apps not on a system dir, because those
10085            // are the only ones that can fail an install due to this.  We
10086            // will take care of the system apps by updating all of their
10087            // library paths after the scan is done. Also during the initial
10088            // scan don't update any libs as we do this wholesale after all
10089            // apps are scanned to avoid dependency based scanning.
10090            updateSharedLibrariesLPr(pkg, null);
10091        }
10092
10093        // All versions of a static shared library are referenced with the same
10094        // package name. Internally, we use a synthetic package name to allow
10095        // multiple versions of the same shared library to be installed. So,
10096        // we need to generate the synthetic package name of the latest shared
10097        // library in order to compare signatures.
10098        PackageSetting signatureCheckPs = pkgSetting;
10099        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10100            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10101            if (libraryEntry != null) {
10102                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10103            }
10104        }
10105
10106        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10107        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10108            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10109                // We just determined the app is signed correctly, so bring
10110                // over the latest parsed certs.
10111                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10112            } else {
10113                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10114                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10115                            "Package " + pkg.packageName + " upgrade keys do not match the "
10116                                    + "previously installed version");
10117                } else {
10118                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10119                    String msg = "System package " + pkg.packageName
10120                            + " signature changed; retaining data.";
10121                    reportSettingsProblem(Log.WARN, msg);
10122                }
10123            }
10124        } else {
10125            try {
10126                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10127                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10128                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10129                        pkg.mSigningDetails, compareCompat, compareRecover);
10130                // The new KeySets will be re-added later in the scanning process.
10131                if (compatMatch) {
10132                    synchronized (mPackages) {
10133                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10134                    }
10135                }
10136                // We just determined the app is signed correctly, so bring
10137                // over the latest parsed certs.
10138                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10139
10140
10141                // if this is is a sharedUser, check to see if the new package is signed by a newer
10142                // signing certificate than the existing one, and if so, copy over the new details
10143                if (signatureCheckPs.sharedUser != null
10144                        && pkg.mSigningDetails.hasAncestor(
10145                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10146                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10147                }
10148            } catch (PackageManagerException e) {
10149                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10150                    throw e;
10151                }
10152                // The signature has changed, but this package is in the system
10153                // image...  let's recover!
10154                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10155                // However...  if this package is part of a shared user, but it
10156                // doesn't match the signature of the shared user, let's fail.
10157                // What this means is that you can't change the signatures
10158                // associated with an overall shared user, which doesn't seem all
10159                // that unreasonable.
10160                if (signatureCheckPs.sharedUser != null) {
10161                    if (compareSignatures(
10162                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10163                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10164                        throw new PackageManagerException(
10165                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10166                                "Signature mismatch for shared user: "
10167                                        + pkgSetting.sharedUser);
10168                    }
10169                }
10170                // File a report about this.
10171                String msg = "System package " + pkg.packageName
10172                        + " signature changed; retaining data.";
10173                reportSettingsProblem(Log.WARN, msg);
10174            } catch (IllegalArgumentException e) {
10175
10176                // should never happen: certs matched when checking, but not when comparing
10177                // old to new for sharedUser
10178                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10179                        "Signing certificates comparison made on incomparable signing details"
10180                        + " but somehow passed verifySignatures!");
10181            }
10182        }
10183
10184        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10185            // This package wants to adopt ownership of permissions from
10186            // another package.
10187            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10188                final String origName = pkg.mAdoptPermissions.get(i);
10189                final PackageSetting orig = mSettings.getPackageLPr(origName);
10190                if (orig != null) {
10191                    if (verifyPackageUpdateLPr(orig, pkg)) {
10192                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10193                                + pkg.packageName);
10194                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10195                    }
10196                }
10197            }
10198        }
10199
10200        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10201            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10202                final String codePathString = changedAbiCodePath.get(i);
10203                try {
10204                    mInstaller.rmdex(codePathString,
10205                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10206                } catch (InstallerException ignored) {
10207                }
10208            }
10209        }
10210
10211        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10212            if (oldPkgSetting != null) {
10213                synchronized (mPackages) {
10214                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10215                }
10216            }
10217        } else {
10218            final int userId = user == null ? 0 : user.getIdentifier();
10219            // Modify state for the given package setting
10220            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10221                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10222            if (pkgSetting.getInstantApp(userId)) {
10223                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10224            }
10225        }
10226    }
10227
10228    /**
10229     * Returns the "real" name of the package.
10230     * <p>This may differ from the package's actual name if the application has already
10231     * been installed under one of this package's original names.
10232     */
10233    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10234            @Nullable String renamedPkgName) {
10235        if (isPackageRenamed(pkg, renamedPkgName)) {
10236            return pkg.mRealPackage;
10237        }
10238        return null;
10239    }
10240
10241    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10242    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10243            @Nullable String renamedPkgName) {
10244        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10245    }
10246
10247    /**
10248     * Returns the original package setting.
10249     * <p>A package can migrate its name during an update. In this scenario, a package
10250     * designates a set of names that it considers as one of its original names.
10251     * <p>An original package must be signed identically and it must have the same
10252     * shared user [if any].
10253     */
10254    @GuardedBy("mPackages")
10255    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10256            @Nullable String renamedPkgName) {
10257        if (!isPackageRenamed(pkg, renamedPkgName)) {
10258            return null;
10259        }
10260        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10261            final PackageSetting originalPs =
10262                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10263            if (originalPs != null) {
10264                // the package is already installed under its original name...
10265                // but, should we use it?
10266                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10267                    // the new package is incompatible with the original
10268                    continue;
10269                } else if (originalPs.sharedUser != null) {
10270                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10271                        // the shared user id is incompatible with the original
10272                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10273                                + " to " + pkg.packageName + ": old uid "
10274                                + originalPs.sharedUser.name
10275                                + " differs from " + pkg.mSharedUserId);
10276                        continue;
10277                    }
10278                    // TODO: Add case when shared user id is added [b/28144775]
10279                } else {
10280                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10281                            + pkg.packageName + " to old name " + originalPs.name);
10282                }
10283                return originalPs;
10284            }
10285        }
10286        return null;
10287    }
10288
10289    /**
10290     * Renames the package if it was installed under a different name.
10291     * <p>When we've already installed the package under an original name, update
10292     * the new package so we can continue to have the old name.
10293     */
10294    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10295            @NonNull String renamedPackageName) {
10296        if (pkg.mOriginalPackages == null
10297                || !pkg.mOriginalPackages.contains(renamedPackageName)
10298                || pkg.packageName.equals(renamedPackageName)) {
10299            return;
10300        }
10301        pkg.setPackageName(renamedPackageName);
10302    }
10303
10304    /**
10305     * Just scans the package without any side effects.
10306     * <p>Not entirely true at the moment. There is still one side effect -- this
10307     * method potentially modifies a live {@link PackageSetting} object representing
10308     * the package being scanned. This will be resolved in the future.
10309     *
10310     * @param request Information about the package to be scanned
10311     * @param isUnderFactoryTest Whether or not the device is under factory test
10312     * @param currentTime The current time, in millis
10313     * @return The results of the scan
10314     */
10315    @GuardedBy("mInstallLock")
10316    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10317            boolean isUnderFactoryTest, long currentTime)
10318                    throws PackageManagerException {
10319        final PackageParser.Package pkg = request.pkg;
10320        PackageSetting pkgSetting = request.pkgSetting;
10321        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10322        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10323        final @ParseFlags int parseFlags = request.parseFlags;
10324        final @ScanFlags int scanFlags = request.scanFlags;
10325        final String realPkgName = request.realPkgName;
10326        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10327        final UserHandle user = request.user;
10328        final boolean isPlatformPackage = request.isPlatformPackage;
10329
10330        List<String> changedAbiCodePath = null;
10331
10332        if (DEBUG_PACKAGE_SCANNING) {
10333            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10334                Log.d(TAG, "Scanning package " + pkg.packageName);
10335        }
10336
10337        if (Build.IS_DEBUGGABLE &&
10338                pkg.isPrivileged() &&
10339                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10340            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10341        }
10342
10343        // Initialize package source and resource directories
10344        final File scanFile = new File(pkg.codePath);
10345        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10346        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10347
10348        // We keep references to the derived CPU Abis from settings in oder to reuse
10349        // them in the case where we're not upgrading or booting for the first time.
10350        String primaryCpuAbiFromSettings = null;
10351        String secondaryCpuAbiFromSettings = null;
10352        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10353
10354        if (!needToDeriveAbi) {
10355            if (pkgSetting != null) {
10356                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10357                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10358            } else {
10359                // Re-scanning a system package after uninstalling updates; need to derive ABI
10360                needToDeriveAbi = true;
10361            }
10362        }
10363
10364        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10365            PackageManagerService.reportSettingsProblem(Log.WARN,
10366                    "Package " + pkg.packageName + " shared user changed from "
10367                            + (pkgSetting.sharedUser != null
10368                            ? pkgSetting.sharedUser.name : "<nothing>")
10369                            + " to "
10370                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10371                            + "; replacing with new");
10372            pkgSetting = null;
10373        }
10374
10375        String[] usesStaticLibraries = null;
10376        if (pkg.usesStaticLibraries != null) {
10377            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10378            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10379        }
10380        final boolean createNewPackage = (pkgSetting == null);
10381        if (createNewPackage) {
10382            final String parentPackageName = (pkg.parentPackage != null)
10383                    ? pkg.parentPackage.packageName : null;
10384            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10385            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10386            // REMOVE SharedUserSetting from method; update in a separate call
10387            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10388                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10389                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10390                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10391                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10392                    user, true /*allowInstall*/, instantApp, virtualPreload,
10393                    parentPackageName, pkg.getChildPackageNames(),
10394                    UserManagerService.getInstance(), usesStaticLibraries,
10395                    pkg.usesStaticLibrariesVersions);
10396        } else {
10397            // REMOVE SharedUserSetting from method; update in a separate call.
10398            //
10399            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10400            // secondaryCpuAbi are not known at this point so we always update them
10401            // to null here, only to reset them at a later point.
10402            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10403                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10404                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10405                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10406                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10407                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10408        }
10409        if (createNewPackage && originalPkgSetting != null) {
10410            // This is the initial transition from the original package, so,
10411            // fix up the new package's name now. We must do this after looking
10412            // up the package under its new name, so getPackageLP takes care of
10413            // fiddling things correctly.
10414            pkg.setPackageName(originalPkgSetting.name);
10415
10416            // File a report about this.
10417            String msg = "New package " + pkgSetting.realName
10418                    + " renamed to replace old package " + pkgSetting.name;
10419            reportSettingsProblem(Log.WARN, msg);
10420        }
10421
10422        if (disabledPkgSetting != null) {
10423            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10424        }
10425
10426        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10427        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10428        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10429        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10430        // least restrictive selinux domain.
10431        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10432        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10433        // ensures that all packages continue to run in the same selinux domain.
10434        final int targetSdkVersion =
10435            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10436            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10437        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10438        // They currently can be if the sharedUser apps are signed with the platform key.
10439        final boolean isPrivileged = (sharedUserSetting != null) ?
10440            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10441
10442        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10443                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10444
10445        pkg.mExtras = pkgSetting;
10446        pkg.applicationInfo.processName = fixProcessName(
10447                pkg.applicationInfo.packageName,
10448                pkg.applicationInfo.processName);
10449
10450        if (!isPlatformPackage) {
10451            // Get all of our default paths setup
10452            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10453        }
10454
10455        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10456
10457        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10458            if (needToDeriveAbi) {
10459                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10460                final boolean extractNativeLibs = !pkg.isLibrary();
10461                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10462                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10463
10464                // Some system apps still use directory structure for native libraries
10465                // in which case we might end up not detecting abi solely based on apk
10466                // structure. Try to detect abi based on directory structure.
10467                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10468                        pkg.applicationInfo.primaryCpuAbi == null) {
10469                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10470                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10471                }
10472            } else {
10473                // This is not a first boot or an upgrade, don't bother deriving the
10474                // ABI during the scan. Instead, trust the value that was stored in the
10475                // package setting.
10476                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10477                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10478
10479                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10480
10481                if (DEBUG_ABI_SELECTION) {
10482                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10483                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10484                            pkg.applicationInfo.secondaryCpuAbi);
10485                }
10486            }
10487        } else {
10488            if ((scanFlags & SCAN_MOVE) != 0) {
10489                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10490                // but we already have this packages package info in the PackageSetting. We just
10491                // use that and derive the native library path based on the new codepath.
10492                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10493                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10494            }
10495
10496            // Set native library paths again. For moves, the path will be updated based on the
10497            // ABIs we've determined above. For non-moves, the path will be updated based on the
10498            // ABIs we determined during compilation, but the path will depend on the final
10499            // package path (after the rename away from the stage path).
10500            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10501        }
10502
10503        // This is a special case for the "system" package, where the ABI is
10504        // dictated by the zygote configuration (and init.rc). We should keep track
10505        // of this ABI so that we can deal with "normal" applications that run under
10506        // the same UID correctly.
10507        if (isPlatformPackage) {
10508            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10509                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10510        }
10511
10512        // If there's a mismatch between the abi-override in the package setting
10513        // and the abiOverride specified for the install. Warn about this because we
10514        // would've already compiled the app without taking the package setting into
10515        // account.
10516        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10517            if (cpuAbiOverride == null && pkg.packageName != null) {
10518                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10519                        " for package " + pkg.packageName);
10520            }
10521        }
10522
10523        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10524        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10525        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10526
10527        // Copy the derived override back to the parsed package, so that we can
10528        // update the package settings accordingly.
10529        pkg.cpuAbiOverride = cpuAbiOverride;
10530
10531        if (DEBUG_ABI_SELECTION) {
10532            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10533                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10534                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10535        }
10536
10537        // Push the derived path down into PackageSettings so we know what to
10538        // clean up at uninstall time.
10539        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10540
10541        if (DEBUG_ABI_SELECTION) {
10542            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10543                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10544                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10545        }
10546
10547        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10548            // We don't do this here during boot because we can do it all
10549            // at once after scanning all existing packages.
10550            //
10551            // We also do this *before* we perform dexopt on this package, so that
10552            // we can avoid redundant dexopts, and also to make sure we've got the
10553            // code and package path correct.
10554            changedAbiCodePath =
10555                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10556        }
10557
10558        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10559                android.Manifest.permission.FACTORY_TEST)) {
10560            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10561        }
10562
10563        if (isSystemApp(pkg)) {
10564            pkgSetting.isOrphaned = true;
10565        }
10566
10567        // Take care of first install / last update times.
10568        final long scanFileTime = getLastModifiedTime(pkg);
10569        if (currentTime != 0) {
10570            if (pkgSetting.firstInstallTime == 0) {
10571                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10572            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10573                pkgSetting.lastUpdateTime = currentTime;
10574            }
10575        } else if (pkgSetting.firstInstallTime == 0) {
10576            // We need *something*.  Take time time stamp of the file.
10577            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10578        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10579            if (scanFileTime != pkgSetting.timeStamp) {
10580                // A package on the system image has changed; consider this
10581                // to be an update.
10582                pkgSetting.lastUpdateTime = scanFileTime;
10583            }
10584        }
10585        pkgSetting.setTimeStamp(scanFileTime);
10586
10587        pkgSetting.pkg = pkg;
10588        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10589        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10590            pkgSetting.versionCode = pkg.getLongVersionCode();
10591        }
10592        // Update volume if needed
10593        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10594        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10595            Slog.i(PackageManagerService.TAG,
10596                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10597                    + " package " + pkg.packageName
10598                    + " volume from " + pkgSetting.volumeUuid
10599                    + " to " + volumeUuid);
10600            pkgSetting.volumeUuid = volumeUuid;
10601        }
10602
10603        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10604    }
10605
10606    /**
10607     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10608     */
10609    private static boolean apkHasCode(String fileName) {
10610        StrictJarFile jarFile = null;
10611        try {
10612            jarFile = new StrictJarFile(fileName,
10613                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10614            return jarFile.findEntry("classes.dex") != null;
10615        } catch (IOException ignore) {
10616        } finally {
10617            try {
10618                if (jarFile != null) {
10619                    jarFile.close();
10620                }
10621            } catch (IOException ignore) {}
10622        }
10623        return false;
10624    }
10625
10626    /**
10627     * Enforces code policy for the package. This ensures that if an APK has
10628     * declared hasCode="true" in its manifest that the APK actually contains
10629     * code.
10630     *
10631     * @throws PackageManagerException If bytecode could not be found when it should exist
10632     */
10633    private static void assertCodePolicy(PackageParser.Package pkg)
10634            throws PackageManagerException {
10635        final boolean shouldHaveCode =
10636                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10637        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10638            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10639                    "Package " + pkg.baseCodePath + " code is missing");
10640        }
10641
10642        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10643            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10644                final boolean splitShouldHaveCode =
10645                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10646                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10647                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10648                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10649                }
10650            }
10651        }
10652    }
10653
10654    /**
10655     * Applies policy to the parsed package based upon the given policy flags.
10656     * Ensures the package is in a good state.
10657     * <p>
10658     * Implementation detail: This method must NOT have any side effect. It would
10659     * ideally be static, but, it requires locks to read system state.
10660     */
10661    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10662            final @ScanFlags int scanFlags) {
10663        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10664            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10665            if (pkg.applicationInfo.isDirectBootAware()) {
10666                // we're direct boot aware; set for all components
10667                for (PackageParser.Service s : pkg.services) {
10668                    s.info.encryptionAware = s.info.directBootAware = true;
10669                }
10670                for (PackageParser.Provider p : pkg.providers) {
10671                    p.info.encryptionAware = p.info.directBootAware = true;
10672                }
10673                for (PackageParser.Activity a : pkg.activities) {
10674                    a.info.encryptionAware = a.info.directBootAware = true;
10675                }
10676                for (PackageParser.Activity r : pkg.receivers) {
10677                    r.info.encryptionAware = r.info.directBootAware = true;
10678                }
10679            }
10680            if (compressedFileExists(pkg.codePath)) {
10681                pkg.isStub = true;
10682            }
10683        } else {
10684            // non system apps can't be flagged as core
10685            pkg.coreApp = false;
10686            // clear flags not applicable to regular apps
10687            pkg.applicationInfo.flags &=
10688                    ~ApplicationInfo.FLAG_PERSISTENT;
10689            pkg.applicationInfo.privateFlags &=
10690                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10691            pkg.applicationInfo.privateFlags &=
10692                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10693            // cap permission priorities
10694            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10695                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10696                    pkg.permissionGroups.get(i).info.priority = 0;
10697                }
10698            }
10699        }
10700        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10701            // clear protected broadcasts
10702            pkg.protectedBroadcasts = null;
10703            // ignore export request for single user receivers
10704            if (pkg.receivers != null) {
10705                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10706                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10707                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10708                        receiver.info.exported = false;
10709                    }
10710                }
10711            }
10712            // ignore export request for single user services
10713            if (pkg.services != null) {
10714                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10715                    final PackageParser.Service service = pkg.services.get(i);
10716                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10717                        service.info.exported = false;
10718                    }
10719                }
10720            }
10721            // ignore export request for single user providers
10722            if (pkg.providers != null) {
10723                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10724                    final PackageParser.Provider provider = pkg.providers.get(i);
10725                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10726                        provider.info.exported = false;
10727                    }
10728                }
10729            }
10730        }
10731
10732        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10733            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10734        }
10735
10736        if ((scanFlags & SCAN_AS_OEM) != 0) {
10737            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10738        }
10739
10740        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10741            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10742        }
10743
10744        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10745            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10746        }
10747
10748        if (!isSystemApp(pkg)) {
10749            // Only system apps can use these features.
10750            pkg.mOriginalPackages = null;
10751            pkg.mRealPackage = null;
10752            pkg.mAdoptPermissions = null;
10753        }
10754    }
10755
10756    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10757            throws PackageManagerException {
10758        if (object == null) {
10759            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10760        }
10761        return object;
10762    }
10763
10764    /**
10765     * Asserts the parsed package is valid according to the given policy. If the
10766     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10767     * <p>
10768     * Implementation detail: This method must NOT have any side effects. It would
10769     * ideally be static, but, it requires locks to read system state.
10770     *
10771     * @throws PackageManagerException If the package fails any of the validation checks
10772     */
10773    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10774            final @ScanFlags int scanFlags)
10775                    throws PackageManagerException {
10776        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10777            assertCodePolicy(pkg);
10778        }
10779
10780        if (pkg.applicationInfo.getCodePath() == null ||
10781                pkg.applicationInfo.getResourcePath() == null) {
10782            // Bail out. The resource and code paths haven't been set.
10783            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10784                    "Code and resource paths haven't been set correctly");
10785        }
10786
10787        // Make sure we're not adding any bogus keyset info
10788        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10789        ksms.assertScannedPackageValid(pkg);
10790
10791        synchronized (mPackages) {
10792            // The special "android" package can only be defined once
10793            if (pkg.packageName.equals("android")) {
10794                if (mAndroidApplication != null) {
10795                    Slog.w(TAG, "*************************************************");
10796                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10797                    Slog.w(TAG, " codePath=" + pkg.codePath);
10798                    Slog.w(TAG, "*************************************************");
10799                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10800                            "Core android package being redefined.  Skipping.");
10801                }
10802            }
10803
10804            // A package name must be unique; don't allow duplicates
10805            if (mPackages.containsKey(pkg.packageName)) {
10806                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10807                        "Application package " + pkg.packageName
10808                        + " already installed.  Skipping duplicate.");
10809            }
10810
10811            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10812                // Static libs have a synthetic package name containing the version
10813                // but we still want the base name to be unique.
10814                if (mPackages.containsKey(pkg.manifestPackageName)) {
10815                    throw new PackageManagerException(
10816                            "Duplicate static shared lib provider package");
10817                }
10818
10819                // Static shared libraries should have at least O target SDK
10820                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10821                    throw new PackageManagerException(
10822                            "Packages declaring static-shared libs must target O SDK or higher");
10823                }
10824
10825                // Package declaring static a shared lib cannot be instant apps
10826                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10827                    throw new PackageManagerException(
10828                            "Packages declaring static-shared libs cannot be instant apps");
10829                }
10830
10831                // Package declaring static a shared lib cannot be renamed since the package
10832                // name is synthetic and apps can't code around package manager internals.
10833                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10834                    throw new PackageManagerException(
10835                            "Packages declaring static-shared libs cannot be renamed");
10836                }
10837
10838                // Package declaring static a shared lib cannot declare child packages
10839                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10840                    throw new PackageManagerException(
10841                            "Packages declaring static-shared libs cannot have child packages");
10842                }
10843
10844                // Package declaring static a shared lib cannot declare dynamic libs
10845                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10846                    throw new PackageManagerException(
10847                            "Packages declaring static-shared libs cannot declare dynamic libs");
10848                }
10849
10850                // Package declaring static a shared lib cannot declare shared users
10851                if (pkg.mSharedUserId != null) {
10852                    throw new PackageManagerException(
10853                            "Packages declaring static-shared libs cannot declare shared users");
10854                }
10855
10856                // Static shared libs cannot declare activities
10857                if (!pkg.activities.isEmpty()) {
10858                    throw new PackageManagerException(
10859                            "Static shared libs cannot declare activities");
10860                }
10861
10862                // Static shared libs cannot declare services
10863                if (!pkg.services.isEmpty()) {
10864                    throw new PackageManagerException(
10865                            "Static shared libs cannot declare services");
10866                }
10867
10868                // Static shared libs cannot declare providers
10869                if (!pkg.providers.isEmpty()) {
10870                    throw new PackageManagerException(
10871                            "Static shared libs cannot declare content providers");
10872                }
10873
10874                // Static shared libs cannot declare receivers
10875                if (!pkg.receivers.isEmpty()) {
10876                    throw new PackageManagerException(
10877                            "Static shared libs cannot declare broadcast receivers");
10878                }
10879
10880                // Static shared libs cannot declare permission groups
10881                if (!pkg.permissionGroups.isEmpty()) {
10882                    throw new PackageManagerException(
10883                            "Static shared libs cannot declare permission groups");
10884                }
10885
10886                // Static shared libs cannot declare permissions
10887                if (!pkg.permissions.isEmpty()) {
10888                    throw new PackageManagerException(
10889                            "Static shared libs cannot declare permissions");
10890                }
10891
10892                // Static shared libs cannot declare protected broadcasts
10893                if (pkg.protectedBroadcasts != null) {
10894                    throw new PackageManagerException(
10895                            "Static shared libs cannot declare protected broadcasts");
10896                }
10897
10898                // Static shared libs cannot be overlay targets
10899                if (pkg.mOverlayTarget != null) {
10900                    throw new PackageManagerException(
10901                            "Static shared libs cannot be overlay targets");
10902                }
10903
10904                // The version codes must be ordered as lib versions
10905                long minVersionCode = Long.MIN_VALUE;
10906                long maxVersionCode = Long.MAX_VALUE;
10907
10908                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10909                        pkg.staticSharedLibName);
10910                if (versionedLib != null) {
10911                    final int versionCount = versionedLib.size();
10912                    for (int i = 0; i < versionCount; i++) {
10913                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10914                        final long libVersionCode = libInfo.getDeclaringPackage()
10915                                .getLongVersionCode();
10916                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10917                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10918                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10919                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10920                        } else {
10921                            minVersionCode = maxVersionCode = libVersionCode;
10922                            break;
10923                        }
10924                    }
10925                }
10926                if (pkg.getLongVersionCode() < minVersionCode
10927                        || pkg.getLongVersionCode() > maxVersionCode) {
10928                    throw new PackageManagerException("Static shared"
10929                            + " lib version codes must be ordered as lib versions");
10930                }
10931            }
10932
10933            // Only privileged apps and updated privileged apps can add child packages.
10934            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10935                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10936                    throw new PackageManagerException("Only privileged apps can add child "
10937                            + "packages. Ignoring package " + pkg.packageName);
10938                }
10939                final int childCount = pkg.childPackages.size();
10940                for (int i = 0; i < childCount; i++) {
10941                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10942                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10943                            childPkg.packageName)) {
10944                        throw new PackageManagerException("Can't override child of "
10945                                + "another disabled app. Ignoring package " + pkg.packageName);
10946                    }
10947                }
10948            }
10949
10950            // If we're only installing presumed-existing packages, require that the
10951            // scanned APK is both already known and at the path previously established
10952            // for it.  Previously unknown packages we pick up normally, but if we have an
10953            // a priori expectation about this package's install presence, enforce it.
10954            // With a singular exception for new system packages. When an OTA contains
10955            // a new system package, we allow the codepath to change from a system location
10956            // to the user-installed location. If we don't allow this change, any newer,
10957            // user-installed version of the application will be ignored.
10958            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10959                if (mExpectingBetter.containsKey(pkg.packageName)) {
10960                    logCriticalInfo(Log.WARN,
10961                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10962                } else {
10963                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10964                    if (known != null) {
10965                        if (DEBUG_PACKAGE_SCANNING) {
10966                            Log.d(TAG, "Examining " + pkg.codePath
10967                                    + " and requiring known paths " + known.codePathString
10968                                    + " & " + known.resourcePathString);
10969                        }
10970                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10971                                || !pkg.applicationInfo.getResourcePath().equals(
10972                                        known.resourcePathString)) {
10973                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10974                                    "Application package " + pkg.packageName
10975                                    + " found at " + pkg.applicationInfo.getCodePath()
10976                                    + " but expected at " + known.codePathString
10977                                    + "; ignoring.");
10978                        }
10979                    } else {
10980                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10981                                "Application package " + pkg.packageName
10982                                + " not found; ignoring.");
10983                    }
10984                }
10985            }
10986
10987            // Verify that this new package doesn't have any content providers
10988            // that conflict with existing packages.  Only do this if the
10989            // package isn't already installed, since we don't want to break
10990            // things that are installed.
10991            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10992                final int N = pkg.providers.size();
10993                int i;
10994                for (i=0; i<N; i++) {
10995                    PackageParser.Provider p = pkg.providers.get(i);
10996                    if (p.info.authority != null) {
10997                        String names[] = p.info.authority.split(";");
10998                        for (int j = 0; j < names.length; j++) {
10999                            if (mProvidersByAuthority.containsKey(names[j])) {
11000                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11001                                final String otherPackageName =
11002                                        ((other != null && other.getComponentName() != null) ?
11003                                                other.getComponentName().getPackageName() : "?");
11004                                throw new PackageManagerException(
11005                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11006                                        "Can't install because provider name " + names[j]
11007                                                + " (in package " + pkg.applicationInfo.packageName
11008                                                + ") is already used by " + otherPackageName);
11009                            }
11010                        }
11011                    }
11012                }
11013            }
11014
11015            // Verify that packages sharing a user with a privileged app are marked as privileged.
11016            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11017                SharedUserSetting sharedUserSetting = null;
11018                try {
11019                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11020                } catch (PackageManagerException ignore) {}
11021                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11022                    // Exempt SharedUsers signed with the platform key.
11023                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11024                    if ((platformPkgSetting.signatures.mSigningDetails
11025                            != PackageParser.SigningDetails.UNKNOWN)
11026                            && (compareSignatures(
11027                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11028                                    pkg.mSigningDetails.signatures)
11029                                            != PackageManager.SIGNATURE_MATCH)) {
11030                        throw new PackageManagerException("Apps that share a user with a " +
11031                                "privileged app must themselves be marked as privileged. " +
11032                                pkg.packageName + " shares privileged user " +
11033                                pkg.mSharedUserId + ".");
11034                    }
11035                }
11036            }
11037
11038            // Apply policies specific for runtime resource overlays (RROs).
11039            if (pkg.mOverlayTarget != null) {
11040                // System overlays have some restrictions on their use of the 'static' state.
11041                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11042                    // We are scanning a system overlay. This can be the first scan of the
11043                    // system/vendor/oem partition, or an update to the system overlay.
11044                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11045                        // This must be an update to a system overlay.
11046                        final PackageSetting previousPkg = assertNotNull(
11047                                mSettings.getPackageLPr(pkg.packageName),
11048                                "previous package state not present");
11049
11050                        // Static overlays cannot be updated.
11051                        if (previousPkg.pkg.mOverlayIsStatic) {
11052                            throw new PackageManagerException("Overlay " + pkg.packageName +
11053                                    " is static and cannot be upgraded.");
11054                        // Non-static overlays cannot be converted to static overlays.
11055                        } else if (pkg.mOverlayIsStatic) {
11056                            throw new PackageManagerException("Overlay " + pkg.packageName +
11057                                    " cannot be upgraded into a static overlay.");
11058                        }
11059                    }
11060                } else {
11061                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11062                    if (pkg.mOverlayIsStatic) {
11063                        throw new PackageManagerException("Overlay " + pkg.packageName +
11064                                " is static but not pre-installed.");
11065                    }
11066
11067                    // The only case where we allow installation of a non-system overlay is when
11068                    // its signature is signed with the platform certificate.
11069                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11070                    if ((platformPkgSetting.signatures.mSigningDetails
11071                            != PackageParser.SigningDetails.UNKNOWN)
11072                            && (compareSignatures(
11073                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11074                                    pkg.mSigningDetails.signatures)
11075                                            != PackageManager.SIGNATURE_MATCH)) {
11076                        throw new PackageManagerException("Overlay " + pkg.packageName +
11077                                " must be signed with the platform certificate.");
11078                    }
11079                }
11080            }
11081        }
11082    }
11083
11084    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11085            int type, String declaringPackageName, long declaringVersionCode) {
11086        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11087        if (versionedLib == null) {
11088            versionedLib = new LongSparseArray<>();
11089            mSharedLibraries.put(name, versionedLib);
11090            if (type == SharedLibraryInfo.TYPE_STATIC) {
11091                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11092            }
11093        } else if (versionedLib.indexOfKey(version) >= 0) {
11094            return false;
11095        }
11096        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11097                version, type, declaringPackageName, declaringVersionCode);
11098        versionedLib.put(version, libEntry);
11099        return true;
11100    }
11101
11102    private boolean removeSharedLibraryLPw(String name, long version) {
11103        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11104        if (versionedLib == null) {
11105            return false;
11106        }
11107        final int libIdx = versionedLib.indexOfKey(version);
11108        if (libIdx < 0) {
11109            return false;
11110        }
11111        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11112        versionedLib.remove(version);
11113        if (versionedLib.size() <= 0) {
11114            mSharedLibraries.remove(name);
11115            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11116                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11117                        .getPackageName());
11118            }
11119        }
11120        return true;
11121    }
11122
11123    /**
11124     * Adds a scanned package to the system. When this method is finished, the package will
11125     * be available for query, resolution, etc...
11126     */
11127    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11128            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11129        final String pkgName = pkg.packageName;
11130        if (mCustomResolverComponentName != null &&
11131                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11132            setUpCustomResolverActivity(pkg);
11133        }
11134
11135        if (pkg.packageName.equals("android")) {
11136            synchronized (mPackages) {
11137                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11138                    // Set up information for our fall-back user intent resolution activity.
11139                    mPlatformPackage = pkg;
11140                    pkg.mVersionCode = mSdkVersion;
11141                    pkg.mVersionCodeMajor = 0;
11142                    mAndroidApplication = pkg.applicationInfo;
11143                    if (!mResolverReplaced) {
11144                        mResolveActivity.applicationInfo = mAndroidApplication;
11145                        mResolveActivity.name = ResolverActivity.class.getName();
11146                        mResolveActivity.packageName = mAndroidApplication.packageName;
11147                        mResolveActivity.processName = "system:ui";
11148                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11149                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11150                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11151                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11152                        mResolveActivity.exported = true;
11153                        mResolveActivity.enabled = true;
11154                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11155                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11156                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11157                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11158                                | ActivityInfo.CONFIG_ORIENTATION
11159                                | ActivityInfo.CONFIG_KEYBOARD
11160                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11161                        mResolveInfo.activityInfo = mResolveActivity;
11162                        mResolveInfo.priority = 0;
11163                        mResolveInfo.preferredOrder = 0;
11164                        mResolveInfo.match = 0;
11165                        mResolveComponentName = new ComponentName(
11166                                mAndroidApplication.packageName, mResolveActivity.name);
11167                    }
11168                }
11169            }
11170        }
11171
11172        ArrayList<PackageParser.Package> clientLibPkgs = null;
11173        // writer
11174        synchronized (mPackages) {
11175            boolean hasStaticSharedLibs = false;
11176
11177            // Any app can add new static shared libraries
11178            if (pkg.staticSharedLibName != null) {
11179                // Static shared libs don't allow renaming as they have synthetic package
11180                // names to allow install of multiple versions, so use name from manifest.
11181                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11182                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11183                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11184                    hasStaticSharedLibs = true;
11185                } else {
11186                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11187                                + pkg.staticSharedLibName + " already exists; skipping");
11188                }
11189                // Static shared libs cannot be updated once installed since they
11190                // use synthetic package name which includes the version code, so
11191                // not need to update other packages's shared lib dependencies.
11192            }
11193
11194            if (!hasStaticSharedLibs
11195                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11196                // Only system apps can add new dynamic shared libraries.
11197                if (pkg.libraryNames != null) {
11198                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11199                        String name = pkg.libraryNames.get(i);
11200                        boolean allowed = false;
11201                        if (pkg.isUpdatedSystemApp()) {
11202                            // New library entries can only be added through the
11203                            // system image.  This is important to get rid of a lot
11204                            // of nasty edge cases: for example if we allowed a non-
11205                            // system update of the app to add a library, then uninstalling
11206                            // the update would make the library go away, and assumptions
11207                            // we made such as through app install filtering would now
11208                            // have allowed apps on the device which aren't compatible
11209                            // with it.  Better to just have the restriction here, be
11210                            // conservative, and create many fewer cases that can negatively
11211                            // impact the user experience.
11212                            final PackageSetting sysPs = mSettings
11213                                    .getDisabledSystemPkgLPr(pkg.packageName);
11214                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11215                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11216                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11217                                        allowed = true;
11218                                        break;
11219                                    }
11220                                }
11221                            }
11222                        } else {
11223                            allowed = true;
11224                        }
11225                        if (allowed) {
11226                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11227                                    SharedLibraryInfo.VERSION_UNDEFINED,
11228                                    SharedLibraryInfo.TYPE_DYNAMIC,
11229                                    pkg.packageName, pkg.getLongVersionCode())) {
11230                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11231                                        + name + " already exists; skipping");
11232                            }
11233                        } else {
11234                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11235                                    + name + " that is not declared on system image; skipping");
11236                        }
11237                    }
11238
11239                    if ((scanFlags & SCAN_BOOTING) == 0) {
11240                        // If we are not booting, we need to update any applications
11241                        // that are clients of our shared library.  If we are booting,
11242                        // this will all be done once the scan is complete.
11243                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11244                    }
11245                }
11246            }
11247        }
11248
11249        if ((scanFlags & SCAN_BOOTING) != 0) {
11250            // No apps can run during boot scan, so they don't need to be frozen
11251        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11252            // Caller asked to not kill app, so it's probably not frozen
11253        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11254            // Caller asked us to ignore frozen check for some reason; they
11255            // probably didn't know the package name
11256        } else {
11257            // We're doing major surgery on this package, so it better be frozen
11258            // right now to keep it from launching
11259            checkPackageFrozen(pkgName);
11260        }
11261
11262        // Also need to kill any apps that are dependent on the library.
11263        if (clientLibPkgs != null) {
11264            for (int i=0; i<clientLibPkgs.size(); i++) {
11265                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11266                killApplication(clientPkg.applicationInfo.packageName,
11267                        clientPkg.applicationInfo.uid, "update lib");
11268            }
11269        }
11270
11271        // writer
11272        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11273
11274        synchronized (mPackages) {
11275            // We don't expect installation to fail beyond this point
11276
11277            // Add the new setting to mSettings
11278            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11279            // Add the new setting to mPackages
11280            mPackages.put(pkg.applicationInfo.packageName, pkg);
11281            // Make sure we don't accidentally delete its data.
11282            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11283            while (iter.hasNext()) {
11284                PackageCleanItem item = iter.next();
11285                if (pkgName.equals(item.packageName)) {
11286                    iter.remove();
11287                }
11288            }
11289
11290            // Add the package's KeySets to the global KeySetManagerService
11291            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11292            ksms.addScannedPackageLPw(pkg);
11293
11294            int N = pkg.providers.size();
11295            StringBuilder r = null;
11296            int i;
11297            for (i=0; i<N; i++) {
11298                PackageParser.Provider p = pkg.providers.get(i);
11299                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11300                        p.info.processName);
11301                mProviders.addProvider(p);
11302                p.syncable = p.info.isSyncable;
11303                if (p.info.authority != null) {
11304                    String names[] = p.info.authority.split(";");
11305                    p.info.authority = null;
11306                    for (int j = 0; j < names.length; j++) {
11307                        if (j == 1 && p.syncable) {
11308                            // We only want the first authority for a provider to possibly be
11309                            // syncable, so if we already added this provider using a different
11310                            // authority clear the syncable flag. We copy the provider before
11311                            // changing it because the mProviders object contains a reference
11312                            // to a provider that we don't want to change.
11313                            // Only do this for the second authority since the resulting provider
11314                            // object can be the same for all future authorities for this provider.
11315                            p = new PackageParser.Provider(p);
11316                            p.syncable = false;
11317                        }
11318                        if (!mProvidersByAuthority.containsKey(names[j])) {
11319                            mProvidersByAuthority.put(names[j], p);
11320                            if (p.info.authority == null) {
11321                                p.info.authority = names[j];
11322                            } else {
11323                                p.info.authority = p.info.authority + ";" + names[j];
11324                            }
11325                            if (DEBUG_PACKAGE_SCANNING) {
11326                                if (chatty)
11327                                    Log.d(TAG, "Registered content provider: " + names[j]
11328                                            + ", className = " + p.info.name + ", isSyncable = "
11329                                            + p.info.isSyncable);
11330                            }
11331                        } else {
11332                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11333                            Slog.w(TAG, "Skipping provider name " + names[j] +
11334                                    " (in package " + pkg.applicationInfo.packageName +
11335                                    "): name already used by "
11336                                    + ((other != null && other.getComponentName() != null)
11337                                            ? other.getComponentName().getPackageName() : "?"));
11338                        }
11339                    }
11340                }
11341                if (chatty) {
11342                    if (r == null) {
11343                        r = new StringBuilder(256);
11344                    } else {
11345                        r.append(' ');
11346                    }
11347                    r.append(p.info.name);
11348                }
11349            }
11350            if (r != null) {
11351                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11352            }
11353
11354            N = pkg.services.size();
11355            r = null;
11356            for (i=0; i<N; i++) {
11357                PackageParser.Service s = pkg.services.get(i);
11358                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11359                        s.info.processName);
11360                mServices.addService(s);
11361                if (chatty) {
11362                    if (r == null) {
11363                        r = new StringBuilder(256);
11364                    } else {
11365                        r.append(' ');
11366                    }
11367                    r.append(s.info.name);
11368                }
11369            }
11370            if (r != null) {
11371                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11372            }
11373
11374            N = pkg.receivers.size();
11375            r = null;
11376            for (i=0; i<N; i++) {
11377                PackageParser.Activity a = pkg.receivers.get(i);
11378                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11379                        a.info.processName);
11380                mReceivers.addActivity(a, "receiver");
11381                if (chatty) {
11382                    if (r == null) {
11383                        r = new StringBuilder(256);
11384                    } else {
11385                        r.append(' ');
11386                    }
11387                    r.append(a.info.name);
11388                }
11389            }
11390            if (r != null) {
11391                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11392            }
11393
11394            N = pkg.activities.size();
11395            r = null;
11396            for (i=0; i<N; i++) {
11397                PackageParser.Activity a = pkg.activities.get(i);
11398                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11399                        a.info.processName);
11400                mActivities.addActivity(a, "activity");
11401                if (chatty) {
11402                    if (r == null) {
11403                        r = new StringBuilder(256);
11404                    } else {
11405                        r.append(' ');
11406                    }
11407                    r.append(a.info.name);
11408                }
11409            }
11410            if (r != null) {
11411                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11412            }
11413
11414            // Don't allow ephemeral applications to define new permissions groups.
11415            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11416                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11417                        + " ignored: instant apps cannot define new permission groups.");
11418            } else {
11419                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11420            }
11421
11422            // Don't allow ephemeral applications to define new permissions.
11423            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11424                Slog.w(TAG, "Permissions from package " + pkg.packageName
11425                        + " ignored: instant apps cannot define new permissions.");
11426            } else {
11427                mPermissionManager.addAllPermissions(pkg, chatty);
11428            }
11429
11430            N = pkg.instrumentation.size();
11431            r = null;
11432            for (i=0; i<N; i++) {
11433                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11434                a.info.packageName = pkg.applicationInfo.packageName;
11435                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11436                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11437                a.info.splitNames = pkg.splitNames;
11438                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11439                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11440                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11441                a.info.dataDir = pkg.applicationInfo.dataDir;
11442                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11443                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11444                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11445                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11446                mInstrumentation.put(a.getComponentName(), a);
11447                if (chatty) {
11448                    if (r == null) {
11449                        r = new StringBuilder(256);
11450                    } else {
11451                        r.append(' ');
11452                    }
11453                    r.append(a.info.name);
11454                }
11455            }
11456            if (r != null) {
11457                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11458            }
11459
11460            if (pkg.protectedBroadcasts != null) {
11461                N = pkg.protectedBroadcasts.size();
11462                synchronized (mProtectedBroadcasts) {
11463                    for (i = 0; i < N; i++) {
11464                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11465                    }
11466                }
11467            }
11468        }
11469
11470        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11471    }
11472
11473    /**
11474     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11475     * is derived purely on the basis of the contents of {@code scanFile} and
11476     * {@code cpuAbiOverride}.
11477     *
11478     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11479     */
11480    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11481            boolean extractLibs)
11482                    throws PackageManagerException {
11483        // Give ourselves some initial paths; we'll come back for another
11484        // pass once we've determined ABI below.
11485        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11486
11487        // We would never need to extract libs for forward-locked and external packages,
11488        // since the container service will do it for us. We shouldn't attempt to
11489        // extract libs from system app when it was not updated.
11490        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11491                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11492            extractLibs = false;
11493        }
11494
11495        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11496        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11497
11498        NativeLibraryHelper.Handle handle = null;
11499        try {
11500            handle = NativeLibraryHelper.Handle.create(pkg);
11501            // TODO(multiArch): This can be null for apps that didn't go through the
11502            // usual installation process. We can calculate it again, like we
11503            // do during install time.
11504            //
11505            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11506            // unnecessary.
11507            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11508
11509            // Null out the abis so that they can be recalculated.
11510            pkg.applicationInfo.primaryCpuAbi = null;
11511            pkg.applicationInfo.secondaryCpuAbi = null;
11512            if (isMultiArch(pkg.applicationInfo)) {
11513                // Warn if we've set an abiOverride for multi-lib packages..
11514                // By definition, we need to copy both 32 and 64 bit libraries for
11515                // such packages.
11516                if (pkg.cpuAbiOverride != null
11517                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11518                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11519                }
11520
11521                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11522                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11523                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11524                    if (extractLibs) {
11525                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11526                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11527                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11528                                useIsaSpecificSubdirs);
11529                    } else {
11530                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11531                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11532                    }
11533                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11534                }
11535
11536                // Shared library native code should be in the APK zip aligned
11537                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11538                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11539                            "Shared library native lib extraction not supported");
11540                }
11541
11542                maybeThrowExceptionForMultiArchCopy(
11543                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11544
11545                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11546                    if (extractLibs) {
11547                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11548                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11549                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11550                                useIsaSpecificSubdirs);
11551                    } else {
11552                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11553                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11554                    }
11555                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11556                }
11557
11558                maybeThrowExceptionForMultiArchCopy(
11559                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11560
11561                if (abi64 >= 0) {
11562                    // Shared library native libs should be in the APK zip aligned
11563                    if (extractLibs && pkg.isLibrary()) {
11564                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11565                                "Shared library native lib extraction not supported");
11566                    }
11567                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11568                }
11569
11570                if (abi32 >= 0) {
11571                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11572                    if (abi64 >= 0) {
11573                        if (pkg.use32bitAbi) {
11574                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11575                            pkg.applicationInfo.primaryCpuAbi = abi;
11576                        } else {
11577                            pkg.applicationInfo.secondaryCpuAbi = abi;
11578                        }
11579                    } else {
11580                        pkg.applicationInfo.primaryCpuAbi = abi;
11581                    }
11582                }
11583            } else {
11584                String[] abiList = (cpuAbiOverride != null) ?
11585                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11586
11587                // Enable gross and lame hacks for apps that are built with old
11588                // SDK tools. We must scan their APKs for renderscript bitcode and
11589                // not launch them if it's present. Don't bother checking on devices
11590                // that don't have 64 bit support.
11591                boolean needsRenderScriptOverride = false;
11592                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11593                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11594                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11595                    needsRenderScriptOverride = true;
11596                }
11597
11598                final int copyRet;
11599                if (extractLibs) {
11600                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11601                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11602                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11603                } else {
11604                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11605                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11606                }
11607                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11608
11609                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11610                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11611                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11612                }
11613
11614                if (copyRet >= 0) {
11615                    // Shared libraries that have native libs must be multi-architecture
11616                    if (pkg.isLibrary()) {
11617                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11618                                "Shared library with native libs must be multiarch");
11619                    }
11620                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11621                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11622                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11623                } else if (needsRenderScriptOverride) {
11624                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11625                }
11626            }
11627        } catch (IOException ioe) {
11628            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11629        } finally {
11630            IoUtils.closeQuietly(handle);
11631        }
11632
11633        // Now that we've calculated the ABIs and determined if it's an internal app,
11634        // we will go ahead and populate the nativeLibraryPath.
11635        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11636    }
11637
11638    /**
11639     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11640     * i.e, so that all packages can be run inside a single process if required.
11641     *
11642     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11643     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11644     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11645     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11646     * updating a package that belongs to a shared user.
11647     *
11648     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11649     * adds unnecessary complexity.
11650     */
11651    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11652            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11653        List<String> changedAbiCodePath = null;
11654        String requiredInstructionSet = null;
11655        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11656            requiredInstructionSet = VMRuntime.getInstructionSet(
11657                     scannedPackage.applicationInfo.primaryCpuAbi);
11658        }
11659
11660        PackageSetting requirer = null;
11661        for (PackageSetting ps : packagesForUser) {
11662            // If packagesForUser contains scannedPackage, we skip it. This will happen
11663            // when scannedPackage is an update of an existing package. Without this check,
11664            // we will never be able to change the ABI of any package belonging to a shared
11665            // user, even if it's compatible with other packages.
11666            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11667                if (ps.primaryCpuAbiString == null) {
11668                    continue;
11669                }
11670
11671                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11672                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11673                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11674                    // this but there's not much we can do.
11675                    String errorMessage = "Instruction set mismatch, "
11676                            + ((requirer == null) ? "[caller]" : requirer)
11677                            + " requires " + requiredInstructionSet + " whereas " + ps
11678                            + " requires " + instructionSet;
11679                    Slog.w(TAG, errorMessage);
11680                }
11681
11682                if (requiredInstructionSet == null) {
11683                    requiredInstructionSet = instructionSet;
11684                    requirer = ps;
11685                }
11686            }
11687        }
11688
11689        if (requiredInstructionSet != null) {
11690            String adjustedAbi;
11691            if (requirer != null) {
11692                // requirer != null implies that either scannedPackage was null or that scannedPackage
11693                // did not require an ABI, in which case we have to adjust scannedPackage to match
11694                // the ABI of the set (which is the same as requirer's ABI)
11695                adjustedAbi = requirer.primaryCpuAbiString;
11696                if (scannedPackage != null) {
11697                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11698                }
11699            } else {
11700                // requirer == null implies that we're updating all ABIs in the set to
11701                // match scannedPackage.
11702                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11703            }
11704
11705            for (PackageSetting ps : packagesForUser) {
11706                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11707                    if (ps.primaryCpuAbiString != null) {
11708                        continue;
11709                    }
11710
11711                    ps.primaryCpuAbiString = adjustedAbi;
11712                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11713                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11714                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11715                        if (DEBUG_ABI_SELECTION) {
11716                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11717                                    + " (requirer="
11718                                    + (requirer != null ? requirer.pkg : "null")
11719                                    + ", scannedPackage="
11720                                    + (scannedPackage != null ? scannedPackage : "null")
11721                                    + ")");
11722                        }
11723                        if (changedAbiCodePath == null) {
11724                            changedAbiCodePath = new ArrayList<>();
11725                        }
11726                        changedAbiCodePath.add(ps.codePathString);
11727                    }
11728                }
11729            }
11730        }
11731        return changedAbiCodePath;
11732    }
11733
11734    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11735        synchronized (mPackages) {
11736            mResolverReplaced = true;
11737            // Set up information for custom user intent resolution activity.
11738            mResolveActivity.applicationInfo = pkg.applicationInfo;
11739            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11740            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11741            mResolveActivity.processName = pkg.applicationInfo.packageName;
11742            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11743            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11744                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11745            mResolveActivity.theme = 0;
11746            mResolveActivity.exported = true;
11747            mResolveActivity.enabled = true;
11748            mResolveInfo.activityInfo = mResolveActivity;
11749            mResolveInfo.priority = 0;
11750            mResolveInfo.preferredOrder = 0;
11751            mResolveInfo.match = 0;
11752            mResolveComponentName = mCustomResolverComponentName;
11753            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11754                    mResolveComponentName);
11755        }
11756    }
11757
11758    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11759        if (installerActivity == null) {
11760            if (DEBUG_INSTANT) {
11761                Slog.d(TAG, "Clear ephemeral installer activity");
11762            }
11763            mInstantAppInstallerActivity = null;
11764            return;
11765        }
11766
11767        if (DEBUG_INSTANT) {
11768            Slog.d(TAG, "Set ephemeral installer activity: "
11769                    + installerActivity.getComponentName());
11770        }
11771        // Set up information for ephemeral installer activity
11772        mInstantAppInstallerActivity = installerActivity;
11773        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11774                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11775        mInstantAppInstallerActivity.exported = true;
11776        mInstantAppInstallerActivity.enabled = true;
11777        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11778        mInstantAppInstallerInfo.priority = 1;
11779        mInstantAppInstallerInfo.preferredOrder = 1;
11780        mInstantAppInstallerInfo.isDefault = true;
11781        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11782                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11783    }
11784
11785    private static String calculateBundledApkRoot(final String codePathString) {
11786        final File codePath = new File(codePathString);
11787        final File codeRoot;
11788        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11789            codeRoot = Environment.getRootDirectory();
11790        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11791            codeRoot = Environment.getOemDirectory();
11792        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11793            codeRoot = Environment.getVendorDirectory();
11794        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11795            codeRoot = Environment.getOdmDirectory();
11796        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11797            codeRoot = Environment.getProductDirectory();
11798        } else {
11799            // Unrecognized code path; take its top real segment as the apk root:
11800            // e.g. /something/app/blah.apk => /something
11801            try {
11802                File f = codePath.getCanonicalFile();
11803                File parent = f.getParentFile();    // non-null because codePath is a file
11804                File tmp;
11805                while ((tmp = parent.getParentFile()) != null) {
11806                    f = parent;
11807                    parent = tmp;
11808                }
11809                codeRoot = f;
11810                Slog.w(TAG, "Unrecognized code path "
11811                        + codePath + " - using " + codeRoot);
11812            } catch (IOException e) {
11813                // Can't canonicalize the code path -- shenanigans?
11814                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11815                return Environment.getRootDirectory().getPath();
11816            }
11817        }
11818        return codeRoot.getPath();
11819    }
11820
11821    /**
11822     * Derive and set the location of native libraries for the given package,
11823     * which varies depending on where and how the package was installed.
11824     */
11825    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11826        final ApplicationInfo info = pkg.applicationInfo;
11827        final String codePath = pkg.codePath;
11828        final File codeFile = new File(codePath);
11829        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11830        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11831
11832        info.nativeLibraryRootDir = null;
11833        info.nativeLibraryRootRequiresIsa = false;
11834        info.nativeLibraryDir = null;
11835        info.secondaryNativeLibraryDir = null;
11836
11837        if (isApkFile(codeFile)) {
11838            // Monolithic install
11839            if (bundledApp) {
11840                // If "/system/lib64/apkname" exists, assume that is the per-package
11841                // native library directory to use; otherwise use "/system/lib/apkname".
11842                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11843                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11844                        getPrimaryInstructionSet(info));
11845
11846                // This is a bundled system app so choose the path based on the ABI.
11847                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11848                // is just the default path.
11849                final String apkName = deriveCodePathName(codePath);
11850                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11851                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11852                        apkName).getAbsolutePath();
11853
11854                if (info.secondaryCpuAbi != null) {
11855                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11856                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11857                            secondaryLibDir, apkName).getAbsolutePath();
11858                }
11859            } else if (asecApp) {
11860                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11861                        .getAbsolutePath();
11862            } else {
11863                final String apkName = deriveCodePathName(codePath);
11864                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11865                        .getAbsolutePath();
11866            }
11867
11868            info.nativeLibraryRootRequiresIsa = false;
11869            info.nativeLibraryDir = info.nativeLibraryRootDir;
11870        } else {
11871            // Cluster install
11872            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11873            info.nativeLibraryRootRequiresIsa = true;
11874
11875            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11876                    getPrimaryInstructionSet(info)).getAbsolutePath();
11877
11878            if (info.secondaryCpuAbi != null) {
11879                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11880                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11881            }
11882        }
11883    }
11884
11885    /**
11886     * Calculate the abis and roots for a bundled app. These can uniquely
11887     * be determined from the contents of the system partition, i.e whether
11888     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11889     * of this information, and instead assume that the system was built
11890     * sensibly.
11891     */
11892    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11893                                           PackageSetting pkgSetting) {
11894        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11895
11896        // If "/system/lib64/apkname" exists, assume that is the per-package
11897        // native library directory to use; otherwise use "/system/lib/apkname".
11898        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11899        setBundledAppAbi(pkg, apkRoot, apkName);
11900        // pkgSetting might be null during rescan following uninstall of updates
11901        // to a bundled app, so accommodate that possibility.  The settings in
11902        // that case will be established later from the parsed package.
11903        //
11904        // If the settings aren't null, sync them up with what we've just derived.
11905        // note that apkRoot isn't stored in the package settings.
11906        if (pkgSetting != null) {
11907            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11908            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11909        }
11910    }
11911
11912    /**
11913     * Deduces the ABI of a bundled app and sets the relevant fields on the
11914     * parsed pkg object.
11915     *
11916     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11917     *        under which system libraries are installed.
11918     * @param apkName the name of the installed package.
11919     */
11920    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11921        final File codeFile = new File(pkg.codePath);
11922
11923        final boolean has64BitLibs;
11924        final boolean has32BitLibs;
11925        if (isApkFile(codeFile)) {
11926            // Monolithic install
11927            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11928            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11929        } else {
11930            // Cluster install
11931            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11932            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11933                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11934                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11935                has64BitLibs = (new File(rootDir, isa)).exists();
11936            } else {
11937                has64BitLibs = false;
11938            }
11939            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11940                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11941                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11942                has32BitLibs = (new File(rootDir, isa)).exists();
11943            } else {
11944                has32BitLibs = false;
11945            }
11946        }
11947
11948        if (has64BitLibs && !has32BitLibs) {
11949            // The package has 64 bit libs, but not 32 bit libs. Its primary
11950            // ABI should be 64 bit. We can safely assume here that the bundled
11951            // native libraries correspond to the most preferred ABI in the list.
11952
11953            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11954            pkg.applicationInfo.secondaryCpuAbi = null;
11955        } else if (has32BitLibs && !has64BitLibs) {
11956            // The package has 32 bit libs but not 64 bit libs. Its primary
11957            // ABI should be 32 bit.
11958
11959            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11960            pkg.applicationInfo.secondaryCpuAbi = null;
11961        } else if (has32BitLibs && has64BitLibs) {
11962            // The application has both 64 and 32 bit bundled libraries. We check
11963            // here that the app declares multiArch support, and warn if it doesn't.
11964            //
11965            // We will be lenient here and record both ABIs. The primary will be the
11966            // ABI that's higher on the list, i.e, a device that's configured to prefer
11967            // 64 bit apps will see a 64 bit primary ABI,
11968
11969            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11970                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11971            }
11972
11973            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11974                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11975                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11976            } else {
11977                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11978                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11979            }
11980        } else {
11981            pkg.applicationInfo.primaryCpuAbi = null;
11982            pkg.applicationInfo.secondaryCpuAbi = null;
11983        }
11984    }
11985
11986    private void killApplication(String pkgName, int appId, String reason) {
11987        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11988    }
11989
11990    private void killApplication(String pkgName, int appId, int userId, String reason) {
11991        // Request the ActivityManager to kill the process(only for existing packages)
11992        // so that we do not end up in a confused state while the user is still using the older
11993        // version of the application while the new one gets installed.
11994        final long token = Binder.clearCallingIdentity();
11995        try {
11996            IActivityManager am = ActivityManager.getService();
11997            if (am != null) {
11998                try {
11999                    am.killApplication(pkgName, appId, userId, reason);
12000                } catch (RemoteException e) {
12001                }
12002            }
12003        } finally {
12004            Binder.restoreCallingIdentity(token);
12005        }
12006    }
12007
12008    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12009        // Remove the parent package setting
12010        PackageSetting ps = (PackageSetting) pkg.mExtras;
12011        if (ps != null) {
12012            removePackageLI(ps, chatty);
12013        }
12014        // Remove the child package setting
12015        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12016        for (int i = 0; i < childCount; i++) {
12017            PackageParser.Package childPkg = pkg.childPackages.get(i);
12018            ps = (PackageSetting) childPkg.mExtras;
12019            if (ps != null) {
12020                removePackageLI(ps, chatty);
12021            }
12022        }
12023    }
12024
12025    void removePackageLI(PackageSetting ps, boolean chatty) {
12026        if (DEBUG_INSTALL) {
12027            if (chatty)
12028                Log.d(TAG, "Removing package " + ps.name);
12029        }
12030
12031        // writer
12032        synchronized (mPackages) {
12033            mPackages.remove(ps.name);
12034            final PackageParser.Package pkg = ps.pkg;
12035            if (pkg != null) {
12036                cleanPackageDataStructuresLILPw(pkg, chatty);
12037            }
12038        }
12039    }
12040
12041    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12042        if (DEBUG_INSTALL) {
12043            if (chatty)
12044                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12045        }
12046
12047        // writer
12048        synchronized (mPackages) {
12049            // Remove the parent package
12050            mPackages.remove(pkg.applicationInfo.packageName);
12051            cleanPackageDataStructuresLILPw(pkg, chatty);
12052
12053            // Remove the child packages
12054            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12055            for (int i = 0; i < childCount; i++) {
12056                PackageParser.Package childPkg = pkg.childPackages.get(i);
12057                mPackages.remove(childPkg.applicationInfo.packageName);
12058                cleanPackageDataStructuresLILPw(childPkg, chatty);
12059            }
12060        }
12061    }
12062
12063    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12064        int N = pkg.providers.size();
12065        StringBuilder r = null;
12066        int i;
12067        for (i=0; i<N; i++) {
12068            PackageParser.Provider p = pkg.providers.get(i);
12069            mProviders.removeProvider(p);
12070            if (p.info.authority == null) {
12071
12072                /* There was another ContentProvider with this authority when
12073                 * this app was installed so this authority is null,
12074                 * Ignore it as we don't have to unregister the provider.
12075                 */
12076                continue;
12077            }
12078            String names[] = p.info.authority.split(";");
12079            for (int j = 0; j < names.length; j++) {
12080                if (mProvidersByAuthority.get(names[j]) == p) {
12081                    mProvidersByAuthority.remove(names[j]);
12082                    if (DEBUG_REMOVE) {
12083                        if (chatty)
12084                            Log.d(TAG, "Unregistered content provider: " + names[j]
12085                                    + ", className = " + p.info.name + ", isSyncable = "
12086                                    + p.info.isSyncable);
12087                    }
12088                }
12089            }
12090            if (DEBUG_REMOVE && chatty) {
12091                if (r == null) {
12092                    r = new StringBuilder(256);
12093                } else {
12094                    r.append(' ');
12095                }
12096                r.append(p.info.name);
12097            }
12098        }
12099        if (r != null) {
12100            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12101        }
12102
12103        N = pkg.services.size();
12104        r = null;
12105        for (i=0; i<N; i++) {
12106            PackageParser.Service s = pkg.services.get(i);
12107            mServices.removeService(s);
12108            if (chatty) {
12109                if (r == null) {
12110                    r = new StringBuilder(256);
12111                } else {
12112                    r.append(' ');
12113                }
12114                r.append(s.info.name);
12115            }
12116        }
12117        if (r != null) {
12118            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12119        }
12120
12121        N = pkg.receivers.size();
12122        r = null;
12123        for (i=0; i<N; i++) {
12124            PackageParser.Activity a = pkg.receivers.get(i);
12125            mReceivers.removeActivity(a, "receiver");
12126            if (DEBUG_REMOVE && chatty) {
12127                if (r == null) {
12128                    r = new StringBuilder(256);
12129                } else {
12130                    r.append(' ');
12131                }
12132                r.append(a.info.name);
12133            }
12134        }
12135        if (r != null) {
12136            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12137        }
12138
12139        N = pkg.activities.size();
12140        r = null;
12141        for (i=0; i<N; i++) {
12142            PackageParser.Activity a = pkg.activities.get(i);
12143            mActivities.removeActivity(a, "activity");
12144            if (DEBUG_REMOVE && chatty) {
12145                if (r == null) {
12146                    r = new StringBuilder(256);
12147                } else {
12148                    r.append(' ');
12149                }
12150                r.append(a.info.name);
12151            }
12152        }
12153        if (r != null) {
12154            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12155        }
12156
12157        mPermissionManager.removeAllPermissions(pkg, chatty);
12158
12159        N = pkg.instrumentation.size();
12160        r = null;
12161        for (i=0; i<N; i++) {
12162            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12163            mInstrumentation.remove(a.getComponentName());
12164            if (DEBUG_REMOVE && chatty) {
12165                if (r == null) {
12166                    r = new StringBuilder(256);
12167                } else {
12168                    r.append(' ');
12169                }
12170                r.append(a.info.name);
12171            }
12172        }
12173        if (r != null) {
12174            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12175        }
12176
12177        r = null;
12178        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12179            // Only system apps can hold shared libraries.
12180            if (pkg.libraryNames != null) {
12181                for (i = 0; i < pkg.libraryNames.size(); i++) {
12182                    String name = pkg.libraryNames.get(i);
12183                    if (removeSharedLibraryLPw(name, 0)) {
12184                        if (DEBUG_REMOVE && chatty) {
12185                            if (r == null) {
12186                                r = new StringBuilder(256);
12187                            } else {
12188                                r.append(' ');
12189                            }
12190                            r.append(name);
12191                        }
12192                    }
12193                }
12194            }
12195        }
12196
12197        r = null;
12198
12199        // Any package can hold static shared libraries.
12200        if (pkg.staticSharedLibName != null) {
12201            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12202                if (DEBUG_REMOVE && chatty) {
12203                    if (r == null) {
12204                        r = new StringBuilder(256);
12205                    } else {
12206                        r.append(' ');
12207                    }
12208                    r.append(pkg.staticSharedLibName);
12209                }
12210            }
12211        }
12212
12213        if (r != null) {
12214            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12215        }
12216    }
12217
12218
12219    final class ActivityIntentResolver
12220            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12221        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12222                boolean defaultOnly, int userId) {
12223            if (!sUserManager.exists(userId)) return null;
12224            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12225            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12226        }
12227
12228        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12229                int userId) {
12230            if (!sUserManager.exists(userId)) return null;
12231            mFlags = flags;
12232            return super.queryIntent(intent, resolvedType,
12233                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12234                    userId);
12235        }
12236
12237        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12238                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12239            if (!sUserManager.exists(userId)) return null;
12240            if (packageActivities == null) {
12241                return null;
12242            }
12243            mFlags = flags;
12244            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12245            final int N = packageActivities.size();
12246            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12247                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12248
12249            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12250            for (int i = 0; i < N; ++i) {
12251                intentFilters = packageActivities.get(i).intents;
12252                if (intentFilters != null && intentFilters.size() > 0) {
12253                    PackageParser.ActivityIntentInfo[] array =
12254                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12255                    intentFilters.toArray(array);
12256                    listCut.add(array);
12257                }
12258            }
12259            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12260        }
12261
12262        /**
12263         * Finds a privileged activity that matches the specified activity names.
12264         */
12265        private PackageParser.Activity findMatchingActivity(
12266                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12267            for (PackageParser.Activity sysActivity : activityList) {
12268                if (sysActivity.info.name.equals(activityInfo.name)) {
12269                    return sysActivity;
12270                }
12271                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12272                    return sysActivity;
12273                }
12274                if (sysActivity.info.targetActivity != null) {
12275                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12276                        return sysActivity;
12277                    }
12278                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12279                        return sysActivity;
12280                    }
12281                }
12282            }
12283            return null;
12284        }
12285
12286        public class IterGenerator<E> {
12287            public Iterator<E> generate(ActivityIntentInfo info) {
12288                return null;
12289            }
12290        }
12291
12292        public class ActionIterGenerator extends IterGenerator<String> {
12293            @Override
12294            public Iterator<String> generate(ActivityIntentInfo info) {
12295                return info.actionsIterator();
12296            }
12297        }
12298
12299        public class CategoriesIterGenerator extends IterGenerator<String> {
12300            @Override
12301            public Iterator<String> generate(ActivityIntentInfo info) {
12302                return info.categoriesIterator();
12303            }
12304        }
12305
12306        public class SchemesIterGenerator extends IterGenerator<String> {
12307            @Override
12308            public Iterator<String> generate(ActivityIntentInfo info) {
12309                return info.schemesIterator();
12310            }
12311        }
12312
12313        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12314            @Override
12315            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12316                return info.authoritiesIterator();
12317            }
12318        }
12319
12320        /**
12321         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12322         * MODIFIED. Do not pass in a list that should not be changed.
12323         */
12324        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12325                IterGenerator<T> generator, Iterator<T> searchIterator) {
12326            // loop through the set of actions; every one must be found in the intent filter
12327            while (searchIterator.hasNext()) {
12328                // we must have at least one filter in the list to consider a match
12329                if (intentList.size() == 0) {
12330                    break;
12331                }
12332
12333                final T searchAction = searchIterator.next();
12334
12335                // loop through the set of intent filters
12336                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12337                while (intentIter.hasNext()) {
12338                    final ActivityIntentInfo intentInfo = intentIter.next();
12339                    boolean selectionFound = false;
12340
12341                    // loop through the intent filter's selection criteria; at least one
12342                    // of them must match the searched criteria
12343                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12344                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12345                        final T intentSelection = intentSelectionIter.next();
12346                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12347                            selectionFound = true;
12348                            break;
12349                        }
12350                    }
12351
12352                    // the selection criteria wasn't found in this filter's set; this filter
12353                    // is not a potential match
12354                    if (!selectionFound) {
12355                        intentIter.remove();
12356                    }
12357                }
12358            }
12359        }
12360
12361        private boolean isProtectedAction(ActivityIntentInfo filter) {
12362            final Iterator<String> actionsIter = filter.actionsIterator();
12363            while (actionsIter != null && actionsIter.hasNext()) {
12364                final String filterAction = actionsIter.next();
12365                if (PROTECTED_ACTIONS.contains(filterAction)) {
12366                    return true;
12367                }
12368            }
12369            return false;
12370        }
12371
12372        /**
12373         * Adjusts the priority of the given intent filter according to policy.
12374         * <p>
12375         * <ul>
12376         * <li>The priority for non privileged applications is capped to '0'</li>
12377         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12378         * <li>The priority for unbundled updates to privileged applications is capped to the
12379         *      priority defined on the system partition</li>
12380         * </ul>
12381         * <p>
12382         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12383         * allowed to obtain any priority on any action.
12384         */
12385        private void adjustPriority(
12386                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12387            // nothing to do; priority is fine as-is
12388            if (intent.getPriority() <= 0) {
12389                return;
12390            }
12391
12392            final ActivityInfo activityInfo = intent.activity.info;
12393            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12394
12395            final boolean privilegedApp =
12396                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12397            if (!privilegedApp) {
12398                // non-privileged applications can never define a priority >0
12399                if (DEBUG_FILTERS) {
12400                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12401                            + " package: " + applicationInfo.packageName
12402                            + " activity: " + intent.activity.className
12403                            + " origPrio: " + intent.getPriority());
12404                }
12405                intent.setPriority(0);
12406                return;
12407            }
12408
12409            if (systemActivities == null) {
12410                // the system package is not disabled; we're parsing the system partition
12411                if (isProtectedAction(intent)) {
12412                    if (mDeferProtectedFilters) {
12413                        // We can't deal with these just yet. No component should ever obtain a
12414                        // >0 priority for a protected actions, with ONE exception -- the setup
12415                        // wizard. The setup wizard, however, cannot be known until we're able to
12416                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12417                        // until all intent filters have been processed. Chicken, meet egg.
12418                        // Let the filter temporarily have a high priority and rectify the
12419                        // priorities after all system packages have been scanned.
12420                        mProtectedFilters.add(intent);
12421                        if (DEBUG_FILTERS) {
12422                            Slog.i(TAG, "Protected action; save for later;"
12423                                    + " package: " + applicationInfo.packageName
12424                                    + " activity: " + intent.activity.className
12425                                    + " origPrio: " + intent.getPriority());
12426                        }
12427                        return;
12428                    } else {
12429                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12430                            Slog.i(TAG, "No setup wizard;"
12431                                + " All protected intents capped to priority 0");
12432                        }
12433                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12434                            if (DEBUG_FILTERS) {
12435                                Slog.i(TAG, "Found setup wizard;"
12436                                    + " allow priority " + intent.getPriority() + ";"
12437                                    + " package: " + intent.activity.info.packageName
12438                                    + " activity: " + intent.activity.className
12439                                    + " priority: " + intent.getPriority());
12440                            }
12441                            // setup wizard gets whatever it wants
12442                            return;
12443                        }
12444                        if (DEBUG_FILTERS) {
12445                            Slog.i(TAG, "Protected action; cap priority to 0;"
12446                                    + " package: " + intent.activity.info.packageName
12447                                    + " activity: " + intent.activity.className
12448                                    + " origPrio: " + intent.getPriority());
12449                        }
12450                        intent.setPriority(0);
12451                        return;
12452                    }
12453                }
12454                // privileged apps on the system image get whatever priority they request
12455                return;
12456            }
12457
12458            // privileged app unbundled update ... try to find the same activity
12459            final PackageParser.Activity foundActivity =
12460                    findMatchingActivity(systemActivities, activityInfo);
12461            if (foundActivity == null) {
12462                // this is a new activity; it cannot obtain >0 priority
12463                if (DEBUG_FILTERS) {
12464                    Slog.i(TAG, "New activity; cap priority to 0;"
12465                            + " package: " + applicationInfo.packageName
12466                            + " activity: " + intent.activity.className
12467                            + " origPrio: " + intent.getPriority());
12468                }
12469                intent.setPriority(0);
12470                return;
12471            }
12472
12473            // found activity, now check for filter equivalence
12474
12475            // a shallow copy is enough; we modify the list, not its contents
12476            final List<ActivityIntentInfo> intentListCopy =
12477                    new ArrayList<>(foundActivity.intents);
12478            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12479
12480            // find matching action subsets
12481            final Iterator<String> actionsIterator = intent.actionsIterator();
12482            if (actionsIterator != null) {
12483                getIntentListSubset(
12484                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12485                if (intentListCopy.size() == 0) {
12486                    // no more intents to match; we're not equivalent
12487                    if (DEBUG_FILTERS) {
12488                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12489                                + " package: " + applicationInfo.packageName
12490                                + " activity: " + intent.activity.className
12491                                + " origPrio: " + intent.getPriority());
12492                    }
12493                    intent.setPriority(0);
12494                    return;
12495                }
12496            }
12497
12498            // find matching category subsets
12499            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12500            if (categoriesIterator != null) {
12501                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12502                        categoriesIterator);
12503                if (intentListCopy.size() == 0) {
12504                    // no more intents to match; we're not equivalent
12505                    if (DEBUG_FILTERS) {
12506                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12507                                + " package: " + applicationInfo.packageName
12508                                + " activity: " + intent.activity.className
12509                                + " origPrio: " + intent.getPriority());
12510                    }
12511                    intent.setPriority(0);
12512                    return;
12513                }
12514            }
12515
12516            // find matching schemes subsets
12517            final Iterator<String> schemesIterator = intent.schemesIterator();
12518            if (schemesIterator != null) {
12519                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12520                        schemesIterator);
12521                if (intentListCopy.size() == 0) {
12522                    // no more intents to match; we're not equivalent
12523                    if (DEBUG_FILTERS) {
12524                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12525                                + " package: " + applicationInfo.packageName
12526                                + " activity: " + intent.activity.className
12527                                + " origPrio: " + intent.getPriority());
12528                    }
12529                    intent.setPriority(0);
12530                    return;
12531                }
12532            }
12533
12534            // find matching authorities subsets
12535            final Iterator<IntentFilter.AuthorityEntry>
12536                    authoritiesIterator = intent.authoritiesIterator();
12537            if (authoritiesIterator != null) {
12538                getIntentListSubset(intentListCopy,
12539                        new AuthoritiesIterGenerator(),
12540                        authoritiesIterator);
12541                if (intentListCopy.size() == 0) {
12542                    // no more intents to match; we're not equivalent
12543                    if (DEBUG_FILTERS) {
12544                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12545                                + " package: " + applicationInfo.packageName
12546                                + " activity: " + intent.activity.className
12547                                + " origPrio: " + intent.getPriority());
12548                    }
12549                    intent.setPriority(0);
12550                    return;
12551                }
12552            }
12553
12554            // we found matching filter(s); app gets the max priority of all intents
12555            int cappedPriority = 0;
12556            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12557                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12558            }
12559            if (intent.getPriority() > cappedPriority) {
12560                if (DEBUG_FILTERS) {
12561                    Slog.i(TAG, "Found matching filter(s);"
12562                            + " cap priority to " + cappedPriority + ";"
12563                            + " package: " + applicationInfo.packageName
12564                            + " activity: " + intent.activity.className
12565                            + " origPrio: " + intent.getPriority());
12566                }
12567                intent.setPriority(cappedPriority);
12568                return;
12569            }
12570            // all this for nothing; the requested priority was <= what was on the system
12571        }
12572
12573        public final void addActivity(PackageParser.Activity a, String type) {
12574            mActivities.put(a.getComponentName(), a);
12575            if (DEBUG_SHOW_INFO)
12576                Log.v(
12577                TAG, "  " + type + " " +
12578                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12579            if (DEBUG_SHOW_INFO)
12580                Log.v(TAG, "    Class=" + a.info.name);
12581            final int NI = a.intents.size();
12582            for (int j=0; j<NI; j++) {
12583                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12584                if ("activity".equals(type)) {
12585                    final PackageSetting ps =
12586                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12587                    final List<PackageParser.Activity> systemActivities =
12588                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12589                    adjustPriority(systemActivities, intent);
12590                }
12591                if (DEBUG_SHOW_INFO) {
12592                    Log.v(TAG, "    IntentFilter:");
12593                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12594                }
12595                if (!intent.debugCheck()) {
12596                    Log.w(TAG, "==> For Activity " + a.info.name);
12597                }
12598                addFilter(intent);
12599            }
12600        }
12601
12602        public final void removeActivity(PackageParser.Activity a, String type) {
12603            mActivities.remove(a.getComponentName());
12604            if (DEBUG_SHOW_INFO) {
12605                Log.v(TAG, "  " + type + " "
12606                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12607                                : a.info.name) + ":");
12608                Log.v(TAG, "    Class=" + a.info.name);
12609            }
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 (DEBUG_SHOW_INFO) {
12614                    Log.v(TAG, "    IntentFilter:");
12615                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12616                }
12617                removeFilter(intent);
12618            }
12619        }
12620
12621        @Override
12622        protected boolean allowFilterResult(
12623                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12624            ActivityInfo filterAi = filter.activity.info;
12625            for (int i=dest.size()-1; i>=0; i--) {
12626                ActivityInfo destAi = dest.get(i).activityInfo;
12627                if (destAi.name == filterAi.name
12628                        && destAi.packageName == filterAi.packageName) {
12629                    return false;
12630                }
12631            }
12632            return true;
12633        }
12634
12635        @Override
12636        protected ActivityIntentInfo[] newArray(int size) {
12637            return new ActivityIntentInfo[size];
12638        }
12639
12640        @Override
12641        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12642            if (!sUserManager.exists(userId)) return true;
12643            PackageParser.Package p = filter.activity.owner;
12644            if (p != null) {
12645                PackageSetting ps = (PackageSetting)p.mExtras;
12646                if (ps != null) {
12647                    // System apps are never considered stopped for purposes of
12648                    // filtering, because there may be no way for the user to
12649                    // actually re-launch them.
12650                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12651                            && ps.getStopped(userId);
12652                }
12653            }
12654            return false;
12655        }
12656
12657        @Override
12658        protected boolean isPackageForFilter(String packageName,
12659                PackageParser.ActivityIntentInfo info) {
12660            return packageName.equals(info.activity.owner.packageName);
12661        }
12662
12663        @Override
12664        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12665                int match, int userId) {
12666            if (!sUserManager.exists(userId)) return null;
12667            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12668                return null;
12669            }
12670            final PackageParser.Activity activity = info.activity;
12671            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12672            if (ps == null) {
12673                return null;
12674            }
12675            final PackageUserState userState = ps.readUserState(userId);
12676            ActivityInfo ai =
12677                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12678            if (ai == null) {
12679                return null;
12680            }
12681            final boolean matchExplicitlyVisibleOnly =
12682                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12683            final boolean matchVisibleToInstantApp =
12684                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12685            final boolean componentVisible =
12686                    matchVisibleToInstantApp
12687                    && info.isVisibleToInstantApp()
12688                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12689            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12690            // throw out filters that aren't visible to ephemeral apps
12691            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12692                return null;
12693            }
12694            // throw out instant app filters if we're not explicitly requesting them
12695            if (!matchInstantApp && userState.instantApp) {
12696                return null;
12697            }
12698            // throw out instant app filters if updates are available; will trigger
12699            // instant app resolution
12700            if (userState.instantApp && ps.isUpdateAvailable()) {
12701                return null;
12702            }
12703            final ResolveInfo res = new ResolveInfo();
12704            res.activityInfo = ai;
12705            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12706                res.filter = info;
12707            }
12708            if (info != null) {
12709                res.handleAllWebDataURI = info.handleAllWebDataURI();
12710            }
12711            res.priority = info.getPriority();
12712            res.preferredOrder = activity.owner.mPreferredOrder;
12713            //System.out.println("Result: " + res.activityInfo.className +
12714            //                   " = " + res.priority);
12715            res.match = match;
12716            res.isDefault = info.hasDefault;
12717            res.labelRes = info.labelRes;
12718            res.nonLocalizedLabel = info.nonLocalizedLabel;
12719            if (userNeedsBadging(userId)) {
12720                res.noResourceId = true;
12721            } else {
12722                res.icon = info.icon;
12723            }
12724            res.iconResourceId = info.icon;
12725            res.system = res.activityInfo.applicationInfo.isSystemApp();
12726            res.isInstantAppAvailable = userState.instantApp;
12727            return res;
12728        }
12729
12730        @Override
12731        protected void sortResults(List<ResolveInfo> results) {
12732            Collections.sort(results, mResolvePrioritySorter);
12733        }
12734
12735        @Override
12736        protected void dumpFilter(PrintWriter out, String prefix,
12737                PackageParser.ActivityIntentInfo filter) {
12738            out.print(prefix); out.print(
12739                    Integer.toHexString(System.identityHashCode(filter.activity)));
12740                    out.print(' ');
12741                    filter.activity.printComponentShortName(out);
12742                    out.print(" filter ");
12743                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12744        }
12745
12746        @Override
12747        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12748            return filter.activity;
12749        }
12750
12751        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12752            PackageParser.Activity activity = (PackageParser.Activity)label;
12753            out.print(prefix); out.print(
12754                    Integer.toHexString(System.identityHashCode(activity)));
12755                    out.print(' ');
12756                    activity.printComponentShortName(out);
12757            if (count > 1) {
12758                out.print(" ("); out.print(count); out.print(" filters)");
12759            }
12760            out.println();
12761        }
12762
12763        // Keys are String (activity class name), values are Activity.
12764        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12765                = new ArrayMap<ComponentName, PackageParser.Activity>();
12766        private int mFlags;
12767    }
12768
12769    private final class ServiceIntentResolver
12770            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12771        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12772                boolean defaultOnly, int userId) {
12773            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12774            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12775        }
12776
12777        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12778                int userId) {
12779            if (!sUserManager.exists(userId)) return null;
12780            mFlags = flags;
12781            return super.queryIntent(intent, resolvedType,
12782                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12783                    userId);
12784        }
12785
12786        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12787                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12788            if (!sUserManager.exists(userId)) return null;
12789            if (packageServices == null) {
12790                return null;
12791            }
12792            mFlags = flags;
12793            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12794            final int N = packageServices.size();
12795            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12796                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12797
12798            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12799            for (int i = 0; i < N; ++i) {
12800                intentFilters = packageServices.get(i).intents;
12801                if (intentFilters != null && intentFilters.size() > 0) {
12802                    PackageParser.ServiceIntentInfo[] array =
12803                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12804                    intentFilters.toArray(array);
12805                    listCut.add(array);
12806                }
12807            }
12808            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12809        }
12810
12811        public final void addService(PackageParser.Service s) {
12812            mServices.put(s.getComponentName(), s);
12813            if (DEBUG_SHOW_INFO) {
12814                Log.v(TAG, "  "
12815                        + (s.info.nonLocalizedLabel != null
12816                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12817                Log.v(TAG, "    Class=" + s.info.name);
12818            }
12819            final int NI = s.intents.size();
12820            int j;
12821            for (j=0; j<NI; j++) {
12822                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12823                if (DEBUG_SHOW_INFO) {
12824                    Log.v(TAG, "    IntentFilter:");
12825                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12826                }
12827                if (!intent.debugCheck()) {
12828                    Log.w(TAG, "==> For Service " + s.info.name);
12829                }
12830                addFilter(intent);
12831            }
12832        }
12833
12834        public final void removeService(PackageParser.Service s) {
12835            mServices.remove(s.getComponentName());
12836            if (DEBUG_SHOW_INFO) {
12837                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12838                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12839                Log.v(TAG, "    Class=" + s.info.name);
12840            }
12841            final int NI = s.intents.size();
12842            int j;
12843            for (j=0; j<NI; j++) {
12844                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12845                if (DEBUG_SHOW_INFO) {
12846                    Log.v(TAG, "    IntentFilter:");
12847                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12848                }
12849                removeFilter(intent);
12850            }
12851        }
12852
12853        @Override
12854        protected boolean allowFilterResult(
12855                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12856            ServiceInfo filterSi = filter.service.info;
12857            for (int i=dest.size()-1; i>=0; i--) {
12858                ServiceInfo destAi = dest.get(i).serviceInfo;
12859                if (destAi.name == filterSi.name
12860                        && destAi.packageName == filterSi.packageName) {
12861                    return false;
12862                }
12863            }
12864            return true;
12865        }
12866
12867        @Override
12868        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12869            return new PackageParser.ServiceIntentInfo[size];
12870        }
12871
12872        @Override
12873        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12874            if (!sUserManager.exists(userId)) return true;
12875            PackageParser.Package p = filter.service.owner;
12876            if (p != null) {
12877                PackageSetting ps = (PackageSetting)p.mExtras;
12878                if (ps != null) {
12879                    // System apps are never considered stopped for purposes of
12880                    // filtering, because there may be no way for the user to
12881                    // actually re-launch them.
12882                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12883                            && ps.getStopped(userId);
12884                }
12885            }
12886            return false;
12887        }
12888
12889        @Override
12890        protected boolean isPackageForFilter(String packageName,
12891                PackageParser.ServiceIntentInfo info) {
12892            return packageName.equals(info.service.owner.packageName);
12893        }
12894
12895        @Override
12896        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12897                int match, int userId) {
12898            if (!sUserManager.exists(userId)) return null;
12899            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12900            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12901                return null;
12902            }
12903            final PackageParser.Service service = info.service;
12904            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12905            if (ps == null) {
12906                return null;
12907            }
12908            final PackageUserState userState = ps.readUserState(userId);
12909            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12910                    userState, userId);
12911            if (si == null) {
12912                return null;
12913            }
12914            final boolean matchVisibleToInstantApp =
12915                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12916            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12917            // throw out filters that aren't visible to ephemeral apps
12918            if (matchVisibleToInstantApp
12919                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12920                return null;
12921            }
12922            // throw out ephemeral filters if we're not explicitly requesting them
12923            if (!isInstantApp && userState.instantApp) {
12924                return null;
12925            }
12926            // throw out instant app filters if updates are available; will trigger
12927            // instant app resolution
12928            if (userState.instantApp && ps.isUpdateAvailable()) {
12929                return null;
12930            }
12931            final ResolveInfo res = new ResolveInfo();
12932            res.serviceInfo = si;
12933            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12934                res.filter = filter;
12935            }
12936            res.priority = info.getPriority();
12937            res.preferredOrder = service.owner.mPreferredOrder;
12938            res.match = match;
12939            res.isDefault = info.hasDefault;
12940            res.labelRes = info.labelRes;
12941            res.nonLocalizedLabel = info.nonLocalizedLabel;
12942            res.icon = info.icon;
12943            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12944            return res;
12945        }
12946
12947        @Override
12948        protected void sortResults(List<ResolveInfo> results) {
12949            Collections.sort(results, mResolvePrioritySorter);
12950        }
12951
12952        @Override
12953        protected void dumpFilter(PrintWriter out, String prefix,
12954                PackageParser.ServiceIntentInfo filter) {
12955            out.print(prefix); out.print(
12956                    Integer.toHexString(System.identityHashCode(filter.service)));
12957                    out.print(' ');
12958                    filter.service.printComponentShortName(out);
12959                    out.print(" filter ");
12960                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12961                    if (filter.service.info.permission != null) {
12962                        out.print(" permission "); out.println(filter.service.info.permission);
12963                    } else {
12964                        out.println();
12965                    }
12966        }
12967
12968        @Override
12969        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12970            return filter.service;
12971        }
12972
12973        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12974            PackageParser.Service service = (PackageParser.Service)label;
12975            out.print(prefix); out.print(
12976                    Integer.toHexString(System.identityHashCode(service)));
12977                    out.print(' ');
12978                    service.printComponentShortName(out);
12979            if (count > 1) {
12980                out.print(" ("); out.print(count); out.print(" filters)");
12981            }
12982            out.println();
12983        }
12984
12985//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12986//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12987//            final List<ResolveInfo> retList = Lists.newArrayList();
12988//            while (i.hasNext()) {
12989//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12990//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12991//                    retList.add(resolveInfo);
12992//                }
12993//            }
12994//            return retList;
12995//        }
12996
12997        // Keys are String (activity class name), values are Activity.
12998        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12999                = new ArrayMap<ComponentName, PackageParser.Service>();
13000        private int mFlags;
13001    }
13002
13003    private final class ProviderIntentResolver
13004            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13005        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13006                boolean defaultOnly, int userId) {
13007            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13008            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13009        }
13010
13011        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13012                int userId) {
13013            if (!sUserManager.exists(userId))
13014                return null;
13015            mFlags = flags;
13016            return super.queryIntent(intent, resolvedType,
13017                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13018                    userId);
13019        }
13020
13021        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13022                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13023            if (!sUserManager.exists(userId))
13024                return null;
13025            if (packageProviders == null) {
13026                return null;
13027            }
13028            mFlags = flags;
13029            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13030            final int N = packageProviders.size();
13031            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13032                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13033
13034            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13035            for (int i = 0; i < N; ++i) {
13036                intentFilters = packageProviders.get(i).intents;
13037                if (intentFilters != null && intentFilters.size() > 0) {
13038                    PackageParser.ProviderIntentInfo[] array =
13039                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13040                    intentFilters.toArray(array);
13041                    listCut.add(array);
13042                }
13043            }
13044            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13045        }
13046
13047        public final void addProvider(PackageParser.Provider p) {
13048            if (mProviders.containsKey(p.getComponentName())) {
13049                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13050                return;
13051            }
13052
13053            mProviders.put(p.getComponentName(), p);
13054            if (DEBUG_SHOW_INFO) {
13055                Log.v(TAG, "  "
13056                        + (p.info.nonLocalizedLabel != null
13057                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13058                Log.v(TAG, "    Class=" + p.info.name);
13059            }
13060            final int NI = p.intents.size();
13061            int j;
13062            for (j = 0; j < NI; j++) {
13063                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13064                if (DEBUG_SHOW_INFO) {
13065                    Log.v(TAG, "    IntentFilter:");
13066                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13067                }
13068                if (!intent.debugCheck()) {
13069                    Log.w(TAG, "==> For Provider " + p.info.name);
13070                }
13071                addFilter(intent);
13072            }
13073        }
13074
13075        public final void removeProvider(PackageParser.Provider p) {
13076            mProviders.remove(p.getComponentName());
13077            if (DEBUG_SHOW_INFO) {
13078                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13079                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13080                Log.v(TAG, "    Class=" + p.info.name);
13081            }
13082            final int NI = p.intents.size();
13083            int j;
13084            for (j = 0; j < NI; j++) {
13085                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13086                if (DEBUG_SHOW_INFO) {
13087                    Log.v(TAG, "    IntentFilter:");
13088                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13089                }
13090                removeFilter(intent);
13091            }
13092        }
13093
13094        @Override
13095        protected boolean allowFilterResult(
13096                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13097            ProviderInfo filterPi = filter.provider.info;
13098            for (int i = dest.size() - 1; i >= 0; i--) {
13099                ProviderInfo destPi = dest.get(i).providerInfo;
13100                if (destPi.name == filterPi.name
13101                        && destPi.packageName == filterPi.packageName) {
13102                    return false;
13103                }
13104            }
13105            return true;
13106        }
13107
13108        @Override
13109        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13110            return new PackageParser.ProviderIntentInfo[size];
13111        }
13112
13113        @Override
13114        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13115            if (!sUserManager.exists(userId))
13116                return true;
13117            PackageParser.Package p = filter.provider.owner;
13118            if (p != null) {
13119                PackageSetting ps = (PackageSetting) p.mExtras;
13120                if (ps != null) {
13121                    // System apps are never considered stopped for purposes of
13122                    // filtering, because there may be no way for the user to
13123                    // actually re-launch them.
13124                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13125                            && ps.getStopped(userId);
13126                }
13127            }
13128            return false;
13129        }
13130
13131        @Override
13132        protected boolean isPackageForFilter(String packageName,
13133                PackageParser.ProviderIntentInfo info) {
13134            return packageName.equals(info.provider.owner.packageName);
13135        }
13136
13137        @Override
13138        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13139                int match, int userId) {
13140            if (!sUserManager.exists(userId))
13141                return null;
13142            final PackageParser.ProviderIntentInfo info = filter;
13143            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13144                return null;
13145            }
13146            final PackageParser.Provider provider = info.provider;
13147            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13148            if (ps == null) {
13149                return null;
13150            }
13151            final PackageUserState userState = ps.readUserState(userId);
13152            final boolean matchVisibleToInstantApp =
13153                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13154            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13155            // throw out filters that aren't visible to instant applications
13156            if (matchVisibleToInstantApp
13157                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13158                return null;
13159            }
13160            // throw out instant application filters if we're not explicitly requesting them
13161            if (!isInstantApp && userState.instantApp) {
13162                return null;
13163            }
13164            // throw out instant application filters if updates are available; will trigger
13165            // instant application resolution
13166            if (userState.instantApp && ps.isUpdateAvailable()) {
13167                return null;
13168            }
13169            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13170                    userState, userId);
13171            if (pi == null) {
13172                return null;
13173            }
13174            final ResolveInfo res = new ResolveInfo();
13175            res.providerInfo = pi;
13176            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13177                res.filter = filter;
13178            }
13179            res.priority = info.getPriority();
13180            res.preferredOrder = provider.owner.mPreferredOrder;
13181            res.match = match;
13182            res.isDefault = info.hasDefault;
13183            res.labelRes = info.labelRes;
13184            res.nonLocalizedLabel = info.nonLocalizedLabel;
13185            res.icon = info.icon;
13186            res.system = res.providerInfo.applicationInfo.isSystemApp();
13187            return res;
13188        }
13189
13190        @Override
13191        protected void sortResults(List<ResolveInfo> results) {
13192            Collections.sort(results, mResolvePrioritySorter);
13193        }
13194
13195        @Override
13196        protected void dumpFilter(PrintWriter out, String prefix,
13197                PackageParser.ProviderIntentInfo filter) {
13198            out.print(prefix);
13199            out.print(
13200                    Integer.toHexString(System.identityHashCode(filter.provider)));
13201            out.print(' ');
13202            filter.provider.printComponentShortName(out);
13203            out.print(" filter ");
13204            out.println(Integer.toHexString(System.identityHashCode(filter)));
13205        }
13206
13207        @Override
13208        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13209            return filter.provider;
13210        }
13211
13212        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13213            PackageParser.Provider provider = (PackageParser.Provider)label;
13214            out.print(prefix); out.print(
13215                    Integer.toHexString(System.identityHashCode(provider)));
13216                    out.print(' ');
13217                    provider.printComponentShortName(out);
13218            if (count > 1) {
13219                out.print(" ("); out.print(count); out.print(" filters)");
13220            }
13221            out.println();
13222        }
13223
13224        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13225                = new ArrayMap<ComponentName, PackageParser.Provider>();
13226        private int mFlags;
13227    }
13228
13229    static final class InstantAppIntentResolver
13230            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13231            AuxiliaryResolveInfo.AuxiliaryFilter> {
13232        /**
13233         * The result that has the highest defined order. Ordering applies on a
13234         * per-package basis. Mapping is from package name to Pair of order and
13235         * EphemeralResolveInfo.
13236         * <p>
13237         * NOTE: This is implemented as a field variable for convenience and efficiency.
13238         * By having a field variable, we're able to track filter ordering as soon as
13239         * a non-zero order is defined. Otherwise, multiple loops across the result set
13240         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13241         * this needs to be contained entirely within {@link #filterResults}.
13242         */
13243        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13244
13245        @Override
13246        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13247            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13248        }
13249
13250        @Override
13251        protected boolean isPackageForFilter(String packageName,
13252                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13253            return true;
13254        }
13255
13256        @Override
13257        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13258                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13259            if (!sUserManager.exists(userId)) {
13260                return null;
13261            }
13262            final String packageName = responseObj.resolveInfo.getPackageName();
13263            final Integer order = responseObj.getOrder();
13264            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13265                    mOrderResult.get(packageName);
13266            // ordering is enabled and this item's order isn't high enough
13267            if (lastOrderResult != null && lastOrderResult.first >= order) {
13268                return null;
13269            }
13270            final InstantAppResolveInfo res = responseObj.resolveInfo;
13271            if (order > 0) {
13272                // non-zero order, enable ordering
13273                mOrderResult.put(packageName, new Pair<>(order, res));
13274            }
13275            return responseObj;
13276        }
13277
13278        @Override
13279        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13280            // only do work if ordering is enabled [most of the time it won't be]
13281            if (mOrderResult.size() == 0) {
13282                return;
13283            }
13284            int resultSize = results.size();
13285            for (int i = 0; i < resultSize; i++) {
13286                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13287                final String packageName = info.getPackageName();
13288                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13289                if (savedInfo == null) {
13290                    // package doesn't having ordering
13291                    continue;
13292                }
13293                if (savedInfo.second == info) {
13294                    // circled back to the highest ordered item; remove from order list
13295                    mOrderResult.remove(packageName);
13296                    if (mOrderResult.size() == 0) {
13297                        // no more ordered items
13298                        break;
13299                    }
13300                    continue;
13301                }
13302                // item has a worse order, remove it from the result list
13303                results.remove(i);
13304                resultSize--;
13305                i--;
13306            }
13307        }
13308    }
13309
13310    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13311            new Comparator<ResolveInfo>() {
13312        public int compare(ResolveInfo r1, ResolveInfo r2) {
13313            int v1 = r1.priority;
13314            int v2 = r2.priority;
13315            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13316            if (v1 != v2) {
13317                return (v1 > v2) ? -1 : 1;
13318            }
13319            v1 = r1.preferredOrder;
13320            v2 = r2.preferredOrder;
13321            if (v1 != v2) {
13322                return (v1 > v2) ? -1 : 1;
13323            }
13324            if (r1.isDefault != r2.isDefault) {
13325                return r1.isDefault ? -1 : 1;
13326            }
13327            v1 = r1.match;
13328            v2 = r2.match;
13329            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13330            if (v1 != v2) {
13331                return (v1 > v2) ? -1 : 1;
13332            }
13333            if (r1.system != r2.system) {
13334                return r1.system ? -1 : 1;
13335            }
13336            if (r1.activityInfo != null) {
13337                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13338            }
13339            if (r1.serviceInfo != null) {
13340                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13341            }
13342            if (r1.providerInfo != null) {
13343                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13344            }
13345            return 0;
13346        }
13347    };
13348
13349    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13350            new Comparator<ProviderInfo>() {
13351        public int compare(ProviderInfo p1, ProviderInfo p2) {
13352            final int v1 = p1.initOrder;
13353            final int v2 = p2.initOrder;
13354            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13355        }
13356    };
13357
13358    @Override
13359    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13360            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13361            final int[] userIds, int[] instantUserIds) {
13362        mHandler.post(new Runnable() {
13363            @Override
13364            public void run() {
13365                try {
13366                    final IActivityManager am = ActivityManager.getService();
13367                    if (am == null) return;
13368                    final int[] resolvedUserIds;
13369                    if (userIds == null) {
13370                        resolvedUserIds = am.getRunningUserIds();
13371                    } else {
13372                        resolvedUserIds = userIds;
13373                    }
13374                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13375                            resolvedUserIds, false);
13376                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13377                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13378                                instantUserIds, true);
13379                    }
13380                } catch (RemoteException ex) {
13381                }
13382            }
13383        });
13384    }
13385
13386    @Override
13387    public void notifyPackageAdded(String packageName) {
13388        final PackageListObserver[] observers;
13389        synchronized (mPackages) {
13390            if (mPackageListObservers.size() == 0) {
13391                return;
13392            }
13393            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13394        }
13395        for (int i = observers.length - 1; i >= 0; --i) {
13396            observers[i].onPackageAdded(packageName);
13397        }
13398    }
13399
13400    @Override
13401    public void notifyPackageRemoved(String packageName) {
13402        final PackageListObserver[] observers;
13403        synchronized (mPackages) {
13404            if (mPackageListObservers.size() == 0) {
13405                return;
13406            }
13407            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13408        }
13409        for (int i = observers.length - 1; i >= 0; --i) {
13410            observers[i].onPackageRemoved(packageName);
13411        }
13412    }
13413
13414    /**
13415     * Sends a broadcast for the given action.
13416     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13417     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13418     * the system and applications allowed to see instant applications to receive package
13419     * lifecycle events for instant applications.
13420     */
13421    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13422            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13423            int[] userIds, boolean isInstantApp)
13424                    throws RemoteException {
13425        for (int id : userIds) {
13426            final Intent intent = new Intent(action,
13427                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13428            final String[] requiredPermissions =
13429                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13430            if (extras != null) {
13431                intent.putExtras(extras);
13432            }
13433            if (targetPkg != null) {
13434                intent.setPackage(targetPkg);
13435            }
13436            // Modify the UID when posting to other users
13437            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13438            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13439                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13440                intent.putExtra(Intent.EXTRA_UID, uid);
13441            }
13442            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13443            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13444            if (DEBUG_BROADCASTS) {
13445                RuntimeException here = new RuntimeException("here");
13446                here.fillInStackTrace();
13447                Slog.d(TAG, "Sending to user " + id + ": "
13448                        + intent.toShortString(false, true, false, false)
13449                        + " " + intent.getExtras(), here);
13450            }
13451            am.broadcastIntent(null, intent, null, finishedReceiver,
13452                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13453                    null, finishedReceiver != null, false, id);
13454        }
13455    }
13456
13457    /**
13458     * Check if the external storage media is available. This is true if there
13459     * is a mounted external storage medium or if the external storage is
13460     * emulated.
13461     */
13462    private boolean isExternalMediaAvailable() {
13463        return mMediaMounted || Environment.isExternalStorageEmulated();
13464    }
13465
13466    @Override
13467    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13468        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13469            return null;
13470        }
13471        if (!isExternalMediaAvailable()) {
13472                // If the external storage is no longer mounted at this point,
13473                // the caller may not have been able to delete all of this
13474                // packages files and can not delete any more.  Bail.
13475            return null;
13476        }
13477        synchronized (mPackages) {
13478            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13479            if (lastPackage != null) {
13480                pkgs.remove(lastPackage);
13481            }
13482            if (pkgs.size() > 0) {
13483                return pkgs.get(0);
13484            }
13485        }
13486        return null;
13487    }
13488
13489    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13490        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13491                userId, andCode ? 1 : 0, packageName);
13492        if (mSystemReady) {
13493            msg.sendToTarget();
13494        } else {
13495            if (mPostSystemReadyMessages == null) {
13496                mPostSystemReadyMessages = new ArrayList<>();
13497            }
13498            mPostSystemReadyMessages.add(msg);
13499        }
13500    }
13501
13502    void startCleaningPackages() {
13503        // reader
13504        if (!isExternalMediaAvailable()) {
13505            return;
13506        }
13507        synchronized (mPackages) {
13508            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13509                return;
13510            }
13511        }
13512        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13513        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13514        IActivityManager am = ActivityManager.getService();
13515        if (am != null) {
13516            int dcsUid = -1;
13517            synchronized (mPackages) {
13518                if (!mDefaultContainerWhitelisted) {
13519                    mDefaultContainerWhitelisted = true;
13520                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13521                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13522                }
13523            }
13524            try {
13525                if (dcsUid > 0) {
13526                    am.backgroundWhitelistUid(dcsUid);
13527                }
13528                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13529                        UserHandle.USER_SYSTEM);
13530            } catch (RemoteException e) {
13531            }
13532        }
13533    }
13534
13535    /**
13536     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13537     * it is acting on behalf on an enterprise or the user).
13538     *
13539     * Note that the ordering of the conditionals in this method is important. The checks we perform
13540     * are as follows, in this order:
13541     *
13542     * 1) If the install is being performed by a system app, we can trust the app to have set the
13543     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13544     *    what it is.
13545     * 2) If the install is being performed by a device or profile owner app, the install reason
13546     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13547     *    set the install reason correctly. If the app targets an older SDK version where install
13548     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13549     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13550     * 3) In all other cases, the install is being performed by a regular app that is neither part
13551     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13552     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13553     *    set to enterprise policy and if so, change it to unknown instead.
13554     */
13555    private int fixUpInstallReason(String installerPackageName, int installerUid,
13556            int installReason) {
13557        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13558                == PERMISSION_GRANTED) {
13559            // If the install is being performed by a system app, we trust that app to have set the
13560            // install reason correctly.
13561            return installReason;
13562        }
13563
13564        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13565            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13566        if (dpm != null) {
13567            ComponentName owner = null;
13568            try {
13569                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13570                if (owner == null) {
13571                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13572                }
13573            } catch (RemoteException e) {
13574            }
13575            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13576                // If the install is being performed by a device or profile owner, the install
13577                // reason should be enterprise policy.
13578                return PackageManager.INSTALL_REASON_POLICY;
13579            }
13580        }
13581
13582        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13583            // If the install is being performed by a regular app (i.e. neither system app nor
13584            // device or profile owner), we have no reason to believe that the app is acting on
13585            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13586            // change it to unknown instead.
13587            return PackageManager.INSTALL_REASON_UNKNOWN;
13588        }
13589
13590        // If the install is being performed by a regular app and the install reason was set to any
13591        // value but enterprise policy, leave the install reason unchanged.
13592        return installReason;
13593    }
13594
13595    void installStage(String packageName, File stagedDir,
13596            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13597            String installerPackageName, int installerUid, UserHandle user,
13598            PackageParser.SigningDetails signingDetails) {
13599        if (DEBUG_INSTANT) {
13600            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13601                Slog.d(TAG, "Ephemeral install of " + packageName);
13602            }
13603        }
13604        final VerificationInfo verificationInfo = new VerificationInfo(
13605                sessionParams.originatingUri, sessionParams.referrerUri,
13606                sessionParams.originatingUid, installerUid);
13607
13608        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13609
13610        final Message msg = mHandler.obtainMessage(INIT_COPY);
13611        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13612                sessionParams.installReason);
13613        final InstallParams params = new InstallParams(origin, null, observer,
13614                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13615                verificationInfo, user, sessionParams.abiOverride,
13616                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13617        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13618        msg.obj = params;
13619
13620        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13621                System.identityHashCode(msg.obj));
13622        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13623                System.identityHashCode(msg.obj));
13624
13625        mHandler.sendMessage(msg);
13626    }
13627
13628    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13629            int userId) {
13630        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13631        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13632        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13633        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13634        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13635                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13636
13637        // Send a session commit broadcast
13638        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13639        info.installReason = pkgSetting.getInstallReason(userId);
13640        info.appPackageName = packageName;
13641        sendSessionCommitBroadcast(info, userId);
13642    }
13643
13644    @Override
13645    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13646            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13647        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13648            return;
13649        }
13650        Bundle extras = new Bundle(1);
13651        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13652        final int uid = UserHandle.getUid(
13653                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13654        extras.putInt(Intent.EXTRA_UID, uid);
13655
13656        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13657                packageName, extras, 0, null, null, userIds, instantUserIds);
13658        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13659            mHandler.post(() -> {
13660                        for (int userId : userIds) {
13661                            sendBootCompletedBroadcastToSystemApp(
13662                                    packageName, includeStopped, userId);
13663                        }
13664                    }
13665            );
13666        }
13667    }
13668
13669    /**
13670     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13671     * automatically without needing an explicit launch.
13672     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13673     */
13674    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13675            int userId) {
13676        // If user is not running, the app didn't miss any broadcast
13677        if (!mUserManagerInternal.isUserRunning(userId)) {
13678            return;
13679        }
13680        final IActivityManager am = ActivityManager.getService();
13681        try {
13682            // Deliver LOCKED_BOOT_COMPLETED first
13683            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13684                    .setPackage(packageName);
13685            if (includeStopped) {
13686                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13687            }
13688            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13689            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13690                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13691
13692            // Deliver BOOT_COMPLETED only if user is unlocked
13693            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13694                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13695                if (includeStopped) {
13696                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13697                }
13698                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13699                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13700            }
13701        } catch (RemoteException e) {
13702            throw e.rethrowFromSystemServer();
13703        }
13704    }
13705
13706    @Override
13707    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13708            int userId) {
13709        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13710        PackageSetting pkgSetting;
13711        final int callingUid = Binder.getCallingUid();
13712        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13713                true /* requireFullPermission */, true /* checkShell */,
13714                "setApplicationHiddenSetting for user " + userId);
13715
13716        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13717            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13718            return false;
13719        }
13720
13721        long callingId = Binder.clearCallingIdentity();
13722        try {
13723            boolean sendAdded = false;
13724            boolean sendRemoved = false;
13725            // writer
13726            synchronized (mPackages) {
13727                pkgSetting = mSettings.mPackages.get(packageName);
13728                if (pkgSetting == null) {
13729                    return false;
13730                }
13731                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13732                    return false;
13733                }
13734                // Do not allow "android" is being disabled
13735                if ("android".equals(packageName)) {
13736                    Slog.w(TAG, "Cannot hide package: android");
13737                    return false;
13738                }
13739                // Cannot hide static shared libs as they are considered
13740                // a part of the using app (emulating static linking). Also
13741                // static libs are installed always on internal storage.
13742                PackageParser.Package pkg = mPackages.get(packageName);
13743                if (pkg != null && pkg.staticSharedLibName != null) {
13744                    Slog.w(TAG, "Cannot hide package: " + packageName
13745                            + " providing static shared library: "
13746                            + pkg.staticSharedLibName);
13747                    return false;
13748                }
13749                // Only allow protected packages to hide themselves.
13750                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13751                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13752                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13753                    return false;
13754                }
13755
13756                if (pkgSetting.getHidden(userId) != hidden) {
13757                    pkgSetting.setHidden(hidden, userId);
13758                    mSettings.writePackageRestrictionsLPr(userId);
13759                    if (hidden) {
13760                        sendRemoved = true;
13761                    } else {
13762                        sendAdded = true;
13763                    }
13764                }
13765            }
13766            if (sendAdded) {
13767                sendPackageAddedForUser(packageName, pkgSetting, userId);
13768                return true;
13769            }
13770            if (sendRemoved) {
13771                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13772                        "hiding pkg");
13773                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13774                return true;
13775            }
13776        } finally {
13777            Binder.restoreCallingIdentity(callingId);
13778        }
13779        return false;
13780    }
13781
13782    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13783            int userId) {
13784        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13785        info.removedPackage = packageName;
13786        info.installerPackageName = pkgSetting.installerPackageName;
13787        info.removedUsers = new int[] {userId};
13788        info.broadcastUsers = new int[] {userId};
13789        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13790        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13791    }
13792
13793    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13794        if (pkgList.length > 0) {
13795            Bundle extras = new Bundle(1);
13796            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13797
13798            sendPackageBroadcast(
13799                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13800                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13801                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13802                    new int[] {userId}, null);
13803        }
13804    }
13805
13806    /**
13807     * Returns true if application is not found or there was an error. Otherwise it returns
13808     * the hidden state of the package for the given user.
13809     */
13810    @Override
13811    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13812        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13813        final int callingUid = Binder.getCallingUid();
13814        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13815                true /* requireFullPermission */, false /* checkShell */,
13816                "getApplicationHidden for user " + userId);
13817        PackageSetting ps;
13818        long callingId = Binder.clearCallingIdentity();
13819        try {
13820            // writer
13821            synchronized (mPackages) {
13822                ps = mSettings.mPackages.get(packageName);
13823                if (ps == null) {
13824                    return true;
13825                }
13826                if (filterAppAccessLPr(ps, callingUid, userId)) {
13827                    return true;
13828                }
13829                return ps.getHidden(userId);
13830            }
13831        } finally {
13832            Binder.restoreCallingIdentity(callingId);
13833        }
13834    }
13835
13836    /**
13837     * @hide
13838     */
13839    @Override
13840    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13841            int installReason) {
13842        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13843                null);
13844        PackageSetting pkgSetting;
13845        final int callingUid = Binder.getCallingUid();
13846        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13847                true /* requireFullPermission */, true /* checkShell */,
13848                "installExistingPackage for user " + userId);
13849        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13850            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13851        }
13852
13853        long callingId = Binder.clearCallingIdentity();
13854        try {
13855            boolean installed = false;
13856            final boolean instantApp =
13857                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13858            final boolean fullApp =
13859                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13860
13861            // writer
13862            synchronized (mPackages) {
13863                pkgSetting = mSettings.mPackages.get(packageName);
13864                if (pkgSetting == null) {
13865                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13866                }
13867                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13868                    // only allow the existing package to be used if it's installed as a full
13869                    // application for at least one user
13870                    boolean installAllowed = false;
13871                    for (int checkUserId : sUserManager.getUserIds()) {
13872                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13873                        if (installAllowed) {
13874                            break;
13875                        }
13876                    }
13877                    if (!installAllowed) {
13878                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13879                    }
13880                }
13881                if (!pkgSetting.getInstalled(userId)) {
13882                    pkgSetting.setInstalled(true, userId);
13883                    pkgSetting.setHidden(false, userId);
13884                    pkgSetting.setInstallReason(installReason, userId);
13885                    mSettings.writePackageRestrictionsLPr(userId);
13886                    mSettings.writeKernelMappingLPr(pkgSetting);
13887                    installed = true;
13888                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13889                    // upgrade app from instant to full; we don't allow app downgrade
13890                    installed = true;
13891                }
13892                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13893            }
13894
13895            if (installed) {
13896                if (pkgSetting.pkg != null) {
13897                    synchronized (mInstallLock) {
13898                        // We don't need to freeze for a brand new install
13899                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13900                    }
13901                }
13902                sendPackageAddedForUser(packageName, pkgSetting, userId);
13903                synchronized (mPackages) {
13904                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13905                }
13906            }
13907        } finally {
13908            Binder.restoreCallingIdentity(callingId);
13909        }
13910
13911        return PackageManager.INSTALL_SUCCEEDED;
13912    }
13913
13914    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13915            boolean instantApp, boolean fullApp) {
13916        // no state specified; do nothing
13917        if (!instantApp && !fullApp) {
13918            return;
13919        }
13920        if (userId != UserHandle.USER_ALL) {
13921            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13922                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13923            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13924                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13925            }
13926        } else {
13927            for (int currentUserId : sUserManager.getUserIds()) {
13928                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13929                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13930                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13931                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13932                }
13933            }
13934        }
13935    }
13936
13937    boolean isUserRestricted(int userId, String restrictionKey) {
13938        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13939        if (restrictions.getBoolean(restrictionKey, false)) {
13940            Log.w(TAG, "User is restricted: " + restrictionKey);
13941            return true;
13942        }
13943        return false;
13944    }
13945
13946    @Override
13947    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13948            int userId) {
13949        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13950        final int callingUid = Binder.getCallingUid();
13951        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13952                true /* requireFullPermission */, true /* checkShell */,
13953                "setPackagesSuspended for user " + userId);
13954
13955        if (ArrayUtils.isEmpty(packageNames)) {
13956            return packageNames;
13957        }
13958
13959        // List of package names for whom the suspended state has changed.
13960        List<String> changedPackages = new ArrayList<>(packageNames.length);
13961        // List of package names for whom the suspended state is not set as requested in this
13962        // method.
13963        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13964        long callingId = Binder.clearCallingIdentity();
13965        try {
13966            for (int i = 0; i < packageNames.length; i++) {
13967                String packageName = packageNames[i];
13968                boolean changed = false;
13969                final int appId;
13970                synchronized (mPackages) {
13971                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13972                    if (pkgSetting == null
13973                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13974                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13975                                + "\". Skipping suspending/un-suspending.");
13976                        unactionedPackages.add(packageName);
13977                        continue;
13978                    }
13979                    appId = pkgSetting.appId;
13980                    if (pkgSetting.getSuspended(userId) != suspended) {
13981                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13982                            unactionedPackages.add(packageName);
13983                            continue;
13984                        }
13985                        pkgSetting.setSuspended(suspended, userId);
13986                        mSettings.writePackageRestrictionsLPr(userId);
13987                        changed = true;
13988                        changedPackages.add(packageName);
13989                    }
13990                }
13991
13992                if (changed && suspended) {
13993                    killApplication(packageName, UserHandle.getUid(userId, appId),
13994                            "suspending package");
13995                }
13996            }
13997        } finally {
13998            Binder.restoreCallingIdentity(callingId);
13999        }
14000
14001        if (!changedPackages.isEmpty()) {
14002            sendPackagesSuspendedForUser(changedPackages.toArray(
14003                    new String[changedPackages.size()]), userId, suspended);
14004        }
14005
14006        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14007    }
14008
14009    @Override
14010    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14011        final int callingUid = Binder.getCallingUid();
14012        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14013                true /* requireFullPermission */, false /* checkShell */,
14014                "isPackageSuspendedForUser for user " + userId);
14015        synchronized (mPackages) {
14016            final PackageSetting ps = mSettings.mPackages.get(packageName);
14017            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14018                throw new IllegalArgumentException("Unknown target package: " + packageName);
14019            }
14020            return ps.getSuspended(userId);
14021        }
14022    }
14023
14024    @GuardedBy("mPackages")
14025    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14026        if (isPackageDeviceAdmin(packageName, userId)) {
14027            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14028                    + "\": has an active device admin");
14029            return false;
14030        }
14031
14032        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14033        if (packageName.equals(activeLauncherPackageName)) {
14034            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14035                    + "\": contains the active launcher");
14036            return false;
14037        }
14038
14039        if (packageName.equals(mRequiredInstallerPackage)) {
14040            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14041                    + "\": required for package installation");
14042            return false;
14043        }
14044
14045        if (packageName.equals(mRequiredUninstallerPackage)) {
14046            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14047                    + "\": required for package uninstallation");
14048            return false;
14049        }
14050
14051        if (packageName.equals(mRequiredVerifierPackage)) {
14052            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14053                    + "\": required for package verification");
14054            return false;
14055        }
14056
14057        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14058            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14059                    + "\": is the default dialer");
14060            return false;
14061        }
14062
14063        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14064            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14065                    + "\": protected package");
14066            return false;
14067        }
14068
14069        // Cannot suspend static shared libs as they are considered
14070        // a part of the using app (emulating static linking). Also
14071        // static libs are installed always on internal storage.
14072        PackageParser.Package pkg = mPackages.get(packageName);
14073        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14074            Slog.w(TAG, "Cannot suspend package: " + packageName
14075                    + " providing static shared library: "
14076                    + pkg.staticSharedLibName);
14077            return false;
14078        }
14079
14080        return true;
14081    }
14082
14083    private String getActiveLauncherPackageName(int userId) {
14084        Intent intent = new Intent(Intent.ACTION_MAIN);
14085        intent.addCategory(Intent.CATEGORY_HOME);
14086        ResolveInfo resolveInfo = resolveIntent(
14087                intent,
14088                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14089                PackageManager.MATCH_DEFAULT_ONLY,
14090                userId);
14091
14092        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14093    }
14094
14095    private String getDefaultDialerPackageName(int userId) {
14096        synchronized (mPackages) {
14097            return mSettings.getDefaultDialerPackageNameLPw(userId);
14098        }
14099    }
14100
14101    @Override
14102    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14103        mContext.enforceCallingOrSelfPermission(
14104                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14105                "Only package verification agents can verify applications");
14106
14107        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14108        final PackageVerificationResponse response = new PackageVerificationResponse(
14109                verificationCode, Binder.getCallingUid());
14110        msg.arg1 = id;
14111        msg.obj = response;
14112        mHandler.sendMessage(msg);
14113    }
14114
14115    @Override
14116    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14117            long millisecondsToDelay) {
14118        mContext.enforceCallingOrSelfPermission(
14119                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14120                "Only package verification agents can extend verification timeouts");
14121
14122        final PackageVerificationState state = mPendingVerification.get(id);
14123        final PackageVerificationResponse response = new PackageVerificationResponse(
14124                verificationCodeAtTimeout, Binder.getCallingUid());
14125
14126        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14127            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14128        }
14129        if (millisecondsToDelay < 0) {
14130            millisecondsToDelay = 0;
14131        }
14132        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14133                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14134            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14135        }
14136
14137        if ((state != null) && !state.timeoutExtended()) {
14138            state.extendTimeout();
14139
14140            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14141            msg.arg1 = id;
14142            msg.obj = response;
14143            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14144        }
14145    }
14146
14147    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14148            int verificationCode, UserHandle user) {
14149        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14150        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14151        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14152        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14153        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14154
14155        mContext.sendBroadcastAsUser(intent, user,
14156                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14157    }
14158
14159    private ComponentName matchComponentForVerifier(String packageName,
14160            List<ResolveInfo> receivers) {
14161        ActivityInfo targetReceiver = null;
14162
14163        final int NR = receivers.size();
14164        for (int i = 0; i < NR; i++) {
14165            final ResolveInfo info = receivers.get(i);
14166            if (info.activityInfo == null) {
14167                continue;
14168            }
14169
14170            if (packageName.equals(info.activityInfo.packageName)) {
14171                targetReceiver = info.activityInfo;
14172                break;
14173            }
14174        }
14175
14176        if (targetReceiver == null) {
14177            return null;
14178        }
14179
14180        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14181    }
14182
14183    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14184            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14185        if (pkgInfo.verifiers.length == 0) {
14186            return null;
14187        }
14188
14189        final int N = pkgInfo.verifiers.length;
14190        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14191        for (int i = 0; i < N; i++) {
14192            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14193
14194            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14195                    receivers);
14196            if (comp == null) {
14197                continue;
14198            }
14199
14200            final int verifierUid = getUidForVerifier(verifierInfo);
14201            if (verifierUid == -1) {
14202                continue;
14203            }
14204
14205            if (DEBUG_VERIFY) {
14206                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14207                        + " with the correct signature");
14208            }
14209            sufficientVerifiers.add(comp);
14210            verificationState.addSufficientVerifier(verifierUid);
14211        }
14212
14213        return sufficientVerifiers;
14214    }
14215
14216    private int getUidForVerifier(VerifierInfo verifierInfo) {
14217        synchronized (mPackages) {
14218            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14219            if (pkg == null) {
14220                return -1;
14221            } else if (pkg.mSigningDetails.signatures.length != 1) {
14222                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14223                        + " has more than one signature; ignoring");
14224                return -1;
14225            }
14226
14227            /*
14228             * If the public key of the package's signature does not match
14229             * our expected public key, then this is a different package and
14230             * we should skip.
14231             */
14232
14233            final byte[] expectedPublicKey;
14234            try {
14235                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14236                final PublicKey publicKey = verifierSig.getPublicKey();
14237                expectedPublicKey = publicKey.getEncoded();
14238            } catch (CertificateException e) {
14239                return -1;
14240            }
14241
14242            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14243
14244            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14245                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14246                        + " does not have the expected public key; ignoring");
14247                return -1;
14248            }
14249
14250            return pkg.applicationInfo.uid;
14251        }
14252    }
14253
14254    @Override
14255    public void finishPackageInstall(int token, boolean didLaunch) {
14256        enforceSystemOrRoot("Only the system is allowed to finish installs");
14257
14258        if (DEBUG_INSTALL) {
14259            Slog.v(TAG, "BM finishing package install for " + token);
14260        }
14261        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14262
14263        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14264        mHandler.sendMessage(msg);
14265    }
14266
14267    /**
14268     * Get the verification agent timeout.  Used for both the APK verifier and the
14269     * intent filter verifier.
14270     *
14271     * @return verification timeout in milliseconds
14272     */
14273    private long getVerificationTimeout() {
14274        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14275                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14276                DEFAULT_VERIFICATION_TIMEOUT);
14277    }
14278
14279    /**
14280     * Get the default verification agent response code.
14281     *
14282     * @return default verification response code
14283     */
14284    private int getDefaultVerificationResponse(UserHandle user) {
14285        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14286            return PackageManager.VERIFICATION_REJECT;
14287        }
14288        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14289                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14290                DEFAULT_VERIFICATION_RESPONSE);
14291    }
14292
14293    /**
14294     * Check whether or not package verification has been enabled.
14295     *
14296     * @return true if verification should be performed
14297     */
14298    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14299        if (!DEFAULT_VERIFY_ENABLE) {
14300            return false;
14301        }
14302
14303        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14304
14305        // Check if installing from ADB
14306        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14307            // Do not run verification in a test harness environment
14308            if (ActivityManager.isRunningInTestHarness()) {
14309                return false;
14310            }
14311            if (ensureVerifyAppsEnabled) {
14312                return true;
14313            }
14314            // Check if the developer does not want package verification for ADB installs
14315            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14316                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14317                return false;
14318            }
14319        } else {
14320            // only when not installed from ADB, skip verification for instant apps when
14321            // the installer and verifier are the same.
14322            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14323                if (mInstantAppInstallerActivity != null
14324                        && mInstantAppInstallerActivity.packageName.equals(
14325                                mRequiredVerifierPackage)) {
14326                    try {
14327                        mContext.getSystemService(AppOpsManager.class)
14328                                .checkPackage(installerUid, mRequiredVerifierPackage);
14329                        if (DEBUG_VERIFY) {
14330                            Slog.i(TAG, "disable verification for instant app");
14331                        }
14332                        return false;
14333                    } catch (SecurityException ignore) { }
14334                }
14335            }
14336        }
14337
14338        if (ensureVerifyAppsEnabled) {
14339            return true;
14340        }
14341
14342        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14343                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14344    }
14345
14346    @Override
14347    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14348            throws RemoteException {
14349        mContext.enforceCallingOrSelfPermission(
14350                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14351                "Only intentfilter verification agents can verify applications");
14352
14353        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14354        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14355                Binder.getCallingUid(), verificationCode, failedDomains);
14356        msg.arg1 = id;
14357        msg.obj = response;
14358        mHandler.sendMessage(msg);
14359    }
14360
14361    @Override
14362    public int getIntentVerificationStatus(String packageName, int userId) {
14363        final int callingUid = Binder.getCallingUid();
14364        if (UserHandle.getUserId(callingUid) != userId) {
14365            mContext.enforceCallingOrSelfPermission(
14366                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14367                    "getIntentVerificationStatus" + userId);
14368        }
14369        if (getInstantAppPackageName(callingUid) != null) {
14370            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14371        }
14372        synchronized (mPackages) {
14373            final PackageSetting ps = mSettings.mPackages.get(packageName);
14374            if (ps == null
14375                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14376                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14377            }
14378            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14379        }
14380    }
14381
14382    @Override
14383    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14384        mContext.enforceCallingOrSelfPermission(
14385                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14386
14387        boolean result = false;
14388        synchronized (mPackages) {
14389            final PackageSetting ps = mSettings.mPackages.get(packageName);
14390            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14391                return false;
14392            }
14393            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14394        }
14395        if (result) {
14396            scheduleWritePackageRestrictionsLocked(userId);
14397        }
14398        return result;
14399    }
14400
14401    @Override
14402    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14403            String packageName) {
14404        final int callingUid = Binder.getCallingUid();
14405        if (getInstantAppPackageName(callingUid) != null) {
14406            return ParceledListSlice.emptyList();
14407        }
14408        synchronized (mPackages) {
14409            final PackageSetting ps = mSettings.mPackages.get(packageName);
14410            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14411                return ParceledListSlice.emptyList();
14412            }
14413            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14414        }
14415    }
14416
14417    @Override
14418    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14419        if (TextUtils.isEmpty(packageName)) {
14420            return ParceledListSlice.emptyList();
14421        }
14422        final int callingUid = Binder.getCallingUid();
14423        final int callingUserId = UserHandle.getUserId(callingUid);
14424        synchronized (mPackages) {
14425            PackageParser.Package pkg = mPackages.get(packageName);
14426            if (pkg == null || pkg.activities == null) {
14427                return ParceledListSlice.emptyList();
14428            }
14429            if (pkg.mExtras == null) {
14430                return ParceledListSlice.emptyList();
14431            }
14432            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14433            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14434                return ParceledListSlice.emptyList();
14435            }
14436            final int count = pkg.activities.size();
14437            ArrayList<IntentFilter> result = new ArrayList<>();
14438            for (int n=0; n<count; n++) {
14439                PackageParser.Activity activity = pkg.activities.get(n);
14440                if (activity.intents != null && activity.intents.size() > 0) {
14441                    result.addAll(activity.intents);
14442                }
14443            }
14444            return new ParceledListSlice<>(result);
14445        }
14446    }
14447
14448    @Override
14449    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14450        mContext.enforceCallingOrSelfPermission(
14451                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14452        if (UserHandle.getCallingUserId() != userId) {
14453            mContext.enforceCallingOrSelfPermission(
14454                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14455        }
14456
14457        synchronized (mPackages) {
14458            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14459            if (packageName != null) {
14460                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14461                        packageName, userId);
14462            }
14463            return result;
14464        }
14465    }
14466
14467    @Override
14468    public String getDefaultBrowserPackageName(int userId) {
14469        if (UserHandle.getCallingUserId() != userId) {
14470            mContext.enforceCallingOrSelfPermission(
14471                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14472        }
14473        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14474            return null;
14475        }
14476        synchronized (mPackages) {
14477            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14478        }
14479    }
14480
14481    /**
14482     * Get the "allow unknown sources" setting.
14483     *
14484     * @return the current "allow unknown sources" setting
14485     */
14486    private int getUnknownSourcesSettings() {
14487        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14488                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14489                -1);
14490    }
14491
14492    @Override
14493    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14494        final int callingUid = Binder.getCallingUid();
14495        if (getInstantAppPackageName(callingUid) != null) {
14496            return;
14497        }
14498        // writer
14499        synchronized (mPackages) {
14500            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14501            if (targetPackageSetting == null
14502                    || filterAppAccessLPr(
14503                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14504                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14505            }
14506
14507            PackageSetting installerPackageSetting;
14508            if (installerPackageName != null) {
14509                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14510                if (installerPackageSetting == null) {
14511                    throw new IllegalArgumentException("Unknown installer package: "
14512                            + installerPackageName);
14513                }
14514            } else {
14515                installerPackageSetting = null;
14516            }
14517
14518            Signature[] callerSignature;
14519            Object obj = mSettings.getUserIdLPr(callingUid);
14520            if (obj != null) {
14521                if (obj instanceof SharedUserSetting) {
14522                    callerSignature =
14523                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14524                } else if (obj instanceof PackageSetting) {
14525                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14526                } else {
14527                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14528                }
14529            } else {
14530                throw new SecurityException("Unknown calling UID: " + callingUid);
14531            }
14532
14533            // Verify: can't set installerPackageName to a package that is
14534            // not signed with the same cert as the caller.
14535            if (installerPackageSetting != null) {
14536                if (compareSignatures(callerSignature,
14537                        installerPackageSetting.signatures.mSigningDetails.signatures)
14538                        != PackageManager.SIGNATURE_MATCH) {
14539                    throw new SecurityException(
14540                            "Caller does not have same cert as new installer package "
14541                            + installerPackageName);
14542                }
14543            }
14544
14545            // Verify: if target already has an installer package, it must
14546            // be signed with the same cert as the caller.
14547            if (targetPackageSetting.installerPackageName != null) {
14548                PackageSetting setting = mSettings.mPackages.get(
14549                        targetPackageSetting.installerPackageName);
14550                // If the currently set package isn't valid, then it's always
14551                // okay to change it.
14552                if (setting != null) {
14553                    if (compareSignatures(callerSignature,
14554                            setting.signatures.mSigningDetails.signatures)
14555                            != PackageManager.SIGNATURE_MATCH) {
14556                        throw new SecurityException(
14557                                "Caller does not have same cert as old installer package "
14558                                + targetPackageSetting.installerPackageName);
14559                    }
14560                }
14561            }
14562
14563            // Okay!
14564            targetPackageSetting.installerPackageName = installerPackageName;
14565            if (installerPackageName != null) {
14566                mSettings.mInstallerPackages.add(installerPackageName);
14567            }
14568            scheduleWriteSettingsLocked();
14569        }
14570    }
14571
14572    @Override
14573    public void setApplicationCategoryHint(String packageName, int categoryHint,
14574            String callerPackageName) {
14575        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14576            throw new SecurityException("Instant applications don't have access to this method");
14577        }
14578        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14579                callerPackageName);
14580        synchronized (mPackages) {
14581            PackageSetting ps = mSettings.mPackages.get(packageName);
14582            if (ps == null) {
14583                throw new IllegalArgumentException("Unknown target package " + packageName);
14584            }
14585            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14586                throw new IllegalArgumentException("Unknown target package " + packageName);
14587            }
14588            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14589                throw new IllegalArgumentException("Calling package " + callerPackageName
14590                        + " is not installer for " + packageName);
14591            }
14592
14593            if (ps.categoryHint != categoryHint) {
14594                ps.categoryHint = categoryHint;
14595                scheduleWriteSettingsLocked();
14596            }
14597        }
14598    }
14599
14600    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14601        // Queue up an async operation since the package installation may take a little while.
14602        mHandler.post(new Runnable() {
14603            public void run() {
14604                mHandler.removeCallbacks(this);
14605                 // Result object to be returned
14606                PackageInstalledInfo res = new PackageInstalledInfo();
14607                res.setReturnCode(currentStatus);
14608                res.uid = -1;
14609                res.pkg = null;
14610                res.removedInfo = null;
14611                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14612                    args.doPreInstall(res.returnCode);
14613                    synchronized (mInstallLock) {
14614                        installPackageTracedLI(args, res);
14615                    }
14616                    args.doPostInstall(res.returnCode, res.uid);
14617                }
14618
14619                // A restore should be performed at this point if (a) the install
14620                // succeeded, (b) the operation is not an update, and (c) the new
14621                // package has not opted out of backup participation.
14622                final boolean update = res.removedInfo != null
14623                        && res.removedInfo.removedPackage != null;
14624                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14625                boolean doRestore = !update
14626                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14627
14628                // Set up the post-install work request bookkeeping.  This will be used
14629                // and cleaned up by the post-install event handling regardless of whether
14630                // there's a restore pass performed.  Token values are >= 1.
14631                int token;
14632                if (mNextInstallToken < 0) mNextInstallToken = 1;
14633                token = mNextInstallToken++;
14634
14635                PostInstallData data = new PostInstallData(args, res);
14636                mRunningInstalls.put(token, data);
14637                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14638
14639                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14640                    // Pass responsibility to the Backup Manager.  It will perform a
14641                    // restore if appropriate, then pass responsibility back to the
14642                    // Package Manager to run the post-install observer callbacks
14643                    // and broadcasts.
14644                    IBackupManager bm = IBackupManager.Stub.asInterface(
14645                            ServiceManager.getService(Context.BACKUP_SERVICE));
14646                    if (bm != null) {
14647                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14648                                + " to BM for possible restore");
14649                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14650                        try {
14651                            // TODO: http://b/22388012
14652                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14653                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14654                            } else {
14655                                doRestore = false;
14656                            }
14657                        } catch (RemoteException e) {
14658                            // can't happen; the backup manager is local
14659                        } catch (Exception e) {
14660                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14661                            doRestore = false;
14662                        }
14663                    } else {
14664                        Slog.e(TAG, "Backup Manager not found!");
14665                        doRestore = false;
14666                    }
14667                }
14668
14669                if (!doRestore) {
14670                    // No restore possible, or the Backup Manager was mysteriously not
14671                    // available -- just fire the post-install work request directly.
14672                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14673
14674                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14675
14676                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14677                    mHandler.sendMessage(msg);
14678                }
14679            }
14680        });
14681    }
14682
14683    /**
14684     * Callback from PackageSettings whenever an app is first transitioned out of the
14685     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14686     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14687     * here whether the app is the target of an ongoing install, and only send the
14688     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14689     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14690     * handling.
14691     */
14692    void notifyFirstLaunch(final String packageName, final String installerPackage,
14693            final int userId) {
14694        // Serialize this with the rest of the install-process message chain.  In the
14695        // restore-at-install case, this Runnable will necessarily run before the
14696        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14697        // are coherent.  In the non-restore case, the app has already completed install
14698        // and been launched through some other means, so it is not in a problematic
14699        // state for observers to see the FIRST_LAUNCH signal.
14700        mHandler.post(new Runnable() {
14701            @Override
14702            public void run() {
14703                for (int i = 0; i < mRunningInstalls.size(); i++) {
14704                    final PostInstallData data = mRunningInstalls.valueAt(i);
14705                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14706                        continue;
14707                    }
14708                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14709                        // right package; but is it for the right user?
14710                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14711                            if (userId == data.res.newUsers[uIndex]) {
14712                                if (DEBUG_BACKUP) {
14713                                    Slog.i(TAG, "Package " + packageName
14714                                            + " being restored so deferring FIRST_LAUNCH");
14715                                }
14716                                return;
14717                            }
14718                        }
14719                    }
14720                }
14721                // didn't find it, so not being restored
14722                if (DEBUG_BACKUP) {
14723                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14724                }
14725                final boolean isInstantApp = isInstantApp(packageName, userId);
14726                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14727                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14728                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14729            }
14730        });
14731    }
14732
14733    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14734            int[] userIds, int[] instantUserIds) {
14735        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14736                installerPkg, null, userIds, instantUserIds);
14737    }
14738
14739    private abstract class HandlerParams {
14740        private static final int MAX_RETRIES = 4;
14741
14742        /**
14743         * Number of times startCopy() has been attempted and had a non-fatal
14744         * error.
14745         */
14746        private int mRetries = 0;
14747
14748        /** User handle for the user requesting the information or installation. */
14749        private final UserHandle mUser;
14750        String traceMethod;
14751        int traceCookie;
14752
14753        HandlerParams(UserHandle user) {
14754            mUser = user;
14755        }
14756
14757        UserHandle getUser() {
14758            return mUser;
14759        }
14760
14761        HandlerParams setTraceMethod(String traceMethod) {
14762            this.traceMethod = traceMethod;
14763            return this;
14764        }
14765
14766        HandlerParams setTraceCookie(int traceCookie) {
14767            this.traceCookie = traceCookie;
14768            return this;
14769        }
14770
14771        final boolean startCopy() {
14772            boolean res;
14773            try {
14774                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14775
14776                if (++mRetries > MAX_RETRIES) {
14777                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14778                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14779                    handleServiceError();
14780                    return false;
14781                } else {
14782                    handleStartCopy();
14783                    res = true;
14784                }
14785            } catch (RemoteException e) {
14786                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14787                mHandler.sendEmptyMessage(MCS_RECONNECT);
14788                res = false;
14789            }
14790            handleReturnCode();
14791            return res;
14792        }
14793
14794        final void serviceError() {
14795            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14796            handleServiceError();
14797            handleReturnCode();
14798        }
14799
14800        abstract void handleStartCopy() throws RemoteException;
14801        abstract void handleServiceError();
14802        abstract void handleReturnCode();
14803    }
14804
14805    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14806        for (File path : paths) {
14807            try {
14808                mcs.clearDirectory(path.getAbsolutePath());
14809            } catch (RemoteException e) {
14810            }
14811        }
14812    }
14813
14814    static class OriginInfo {
14815        /**
14816         * Location where install is coming from, before it has been
14817         * copied/renamed into place. This could be a single monolithic APK
14818         * file, or a cluster directory. This location may be untrusted.
14819         */
14820        final File file;
14821
14822        /**
14823         * Flag indicating that {@link #file} or {@link #cid} has already been
14824         * staged, meaning downstream users don't need to defensively copy the
14825         * contents.
14826         */
14827        final boolean staged;
14828
14829        /**
14830         * Flag indicating that {@link #file} or {@link #cid} is an already
14831         * installed app that is being moved.
14832         */
14833        final boolean existing;
14834
14835        final String resolvedPath;
14836        final File resolvedFile;
14837
14838        static OriginInfo fromNothing() {
14839            return new OriginInfo(null, false, false);
14840        }
14841
14842        static OriginInfo fromUntrustedFile(File file) {
14843            return new OriginInfo(file, false, false);
14844        }
14845
14846        static OriginInfo fromExistingFile(File file) {
14847            return new OriginInfo(file, false, true);
14848        }
14849
14850        static OriginInfo fromStagedFile(File file) {
14851            return new OriginInfo(file, true, false);
14852        }
14853
14854        private OriginInfo(File file, boolean staged, boolean existing) {
14855            this.file = file;
14856            this.staged = staged;
14857            this.existing = existing;
14858
14859            if (file != null) {
14860                resolvedPath = file.getAbsolutePath();
14861                resolvedFile = file;
14862            } else {
14863                resolvedPath = null;
14864                resolvedFile = null;
14865            }
14866        }
14867    }
14868
14869    static class MoveInfo {
14870        final int moveId;
14871        final String fromUuid;
14872        final String toUuid;
14873        final String packageName;
14874        final String dataAppName;
14875        final int appId;
14876        final String seinfo;
14877        final int targetSdkVersion;
14878
14879        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14880                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14881            this.moveId = moveId;
14882            this.fromUuid = fromUuid;
14883            this.toUuid = toUuid;
14884            this.packageName = packageName;
14885            this.dataAppName = dataAppName;
14886            this.appId = appId;
14887            this.seinfo = seinfo;
14888            this.targetSdkVersion = targetSdkVersion;
14889        }
14890    }
14891
14892    static class VerificationInfo {
14893        /** A constant used to indicate that a uid value is not present. */
14894        public static final int NO_UID = -1;
14895
14896        /** URI referencing where the package was downloaded from. */
14897        final Uri originatingUri;
14898
14899        /** HTTP referrer URI associated with the originatingURI. */
14900        final Uri referrer;
14901
14902        /** UID of the application that the install request originated from. */
14903        final int originatingUid;
14904
14905        /** UID of application requesting the install */
14906        final int installerUid;
14907
14908        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14909            this.originatingUri = originatingUri;
14910            this.referrer = referrer;
14911            this.originatingUid = originatingUid;
14912            this.installerUid = installerUid;
14913        }
14914    }
14915
14916    class InstallParams extends HandlerParams {
14917        final OriginInfo origin;
14918        final MoveInfo move;
14919        final IPackageInstallObserver2 observer;
14920        int installFlags;
14921        final String installerPackageName;
14922        final String volumeUuid;
14923        private InstallArgs mArgs;
14924        private int mRet;
14925        final String packageAbiOverride;
14926        final String[] grantedRuntimePermissions;
14927        final VerificationInfo verificationInfo;
14928        final PackageParser.SigningDetails signingDetails;
14929        final int installReason;
14930
14931        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14932                int installFlags, String installerPackageName, String volumeUuid,
14933                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14934                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14935            super(user);
14936            this.origin = origin;
14937            this.move = move;
14938            this.observer = observer;
14939            this.installFlags = installFlags;
14940            this.installerPackageName = installerPackageName;
14941            this.volumeUuid = volumeUuid;
14942            this.verificationInfo = verificationInfo;
14943            this.packageAbiOverride = packageAbiOverride;
14944            this.grantedRuntimePermissions = grantedPermissions;
14945            this.signingDetails = signingDetails;
14946            this.installReason = installReason;
14947        }
14948
14949        @Override
14950        public String toString() {
14951            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14952                    + " file=" + origin.file + "}";
14953        }
14954
14955        private int installLocationPolicy(PackageInfoLite pkgLite) {
14956            String packageName = pkgLite.packageName;
14957            int installLocation = pkgLite.installLocation;
14958            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14959            // reader
14960            synchronized (mPackages) {
14961                // Currently installed package which the new package is attempting to replace or
14962                // null if no such package is installed.
14963                PackageParser.Package installedPkg = mPackages.get(packageName);
14964                // Package which currently owns the data which the new package will own if installed.
14965                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14966                // will be null whereas dataOwnerPkg will contain information about the package
14967                // which was uninstalled while keeping its data.
14968                PackageParser.Package dataOwnerPkg = installedPkg;
14969                if (dataOwnerPkg  == null) {
14970                    PackageSetting ps = mSettings.mPackages.get(packageName);
14971                    if (ps != null) {
14972                        dataOwnerPkg = ps.pkg;
14973                    }
14974                }
14975
14976                if (dataOwnerPkg != null) {
14977                    // If installed, the package will get access to data left on the device by its
14978                    // predecessor. As a security measure, this is permited only if this is not a
14979                    // version downgrade or if the predecessor package is marked as debuggable and
14980                    // a downgrade is explicitly requested.
14981                    //
14982                    // On debuggable platform builds, downgrades are permitted even for
14983                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14984                    // not offer security guarantees and thus it's OK to disable some security
14985                    // mechanisms to make debugging/testing easier on those builds. However, even on
14986                    // debuggable builds downgrades of packages are permitted only if requested via
14987                    // installFlags. This is because we aim to keep the behavior of debuggable
14988                    // platform builds as close as possible to the behavior of non-debuggable
14989                    // platform builds.
14990                    final boolean downgradeRequested =
14991                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14992                    final boolean packageDebuggable =
14993                                (dataOwnerPkg.applicationInfo.flags
14994                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14995                    final boolean downgradePermitted =
14996                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14997                    if (!downgradePermitted) {
14998                        try {
14999                            checkDowngrade(dataOwnerPkg, pkgLite);
15000                        } catch (PackageManagerException e) {
15001                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15002                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15003                        }
15004                    }
15005                }
15006
15007                if (installedPkg != null) {
15008                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15009                        // Check for updated system application.
15010                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15011                            if (onSd) {
15012                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15013                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15014                            }
15015                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15016                        } else {
15017                            if (onSd) {
15018                                // Install flag overrides everything.
15019                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15020                            }
15021                            // If current upgrade specifies particular preference
15022                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15023                                // Application explicitly specified internal.
15024                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15025                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15026                                // App explictly prefers external. Let policy decide
15027                            } else {
15028                                // Prefer previous location
15029                                if (isExternal(installedPkg)) {
15030                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15031                                }
15032                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15033                            }
15034                        }
15035                    } else {
15036                        // Invalid install. Return error code
15037                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15038                    }
15039                }
15040            }
15041            // All the special cases have been taken care of.
15042            // Return result based on recommended install location.
15043            if (onSd) {
15044                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15045            }
15046            return pkgLite.recommendedInstallLocation;
15047        }
15048
15049        /*
15050         * Invoke remote method to get package information and install
15051         * location values. Override install location based on default
15052         * policy if needed and then create install arguments based
15053         * on the install location.
15054         */
15055        public void handleStartCopy() throws RemoteException {
15056            int ret = PackageManager.INSTALL_SUCCEEDED;
15057
15058            // If we're already staged, we've firmly committed to an install location
15059            if (origin.staged) {
15060                if (origin.file != null) {
15061                    installFlags |= PackageManager.INSTALL_INTERNAL;
15062                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15063                } else {
15064                    throw new IllegalStateException("Invalid stage location");
15065                }
15066            }
15067
15068            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15069            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15070            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15071            PackageInfoLite pkgLite = null;
15072
15073            if (onInt && onSd) {
15074                // Check if both bits are set.
15075                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15076                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15077            } else if (onSd && ephemeral) {
15078                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15079                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15080            } else {
15081                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15082                        packageAbiOverride);
15083
15084                if (DEBUG_INSTANT && ephemeral) {
15085                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15086                }
15087
15088                /*
15089                 * If we have too little free space, try to free cache
15090                 * before giving up.
15091                 */
15092                if (!origin.staged && pkgLite.recommendedInstallLocation
15093                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15094                    // TODO: focus freeing disk space on the target device
15095                    final StorageManager storage = StorageManager.from(mContext);
15096                    final long lowThreshold = storage.getStorageLowBytes(
15097                            Environment.getDataDirectory());
15098
15099                    final long sizeBytes = mContainerService.calculateInstalledSize(
15100                            origin.resolvedPath, packageAbiOverride);
15101
15102                    try {
15103                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15104                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15105                                installFlags, packageAbiOverride);
15106                    } catch (InstallerException e) {
15107                        Slog.w(TAG, "Failed to free cache", e);
15108                    }
15109
15110                    /*
15111                     * The cache free must have deleted the file we
15112                     * downloaded to install.
15113                     *
15114                     * TODO: fix the "freeCache" call to not delete
15115                     *       the file we care about.
15116                     */
15117                    if (pkgLite.recommendedInstallLocation
15118                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15119                        pkgLite.recommendedInstallLocation
15120                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15121                    }
15122                }
15123            }
15124
15125            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15126                int loc = pkgLite.recommendedInstallLocation;
15127                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15128                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15129                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15130                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15131                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15132                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15133                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15134                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15135                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15136                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15137                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15138                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15139                } else {
15140                    // Override with defaults if needed.
15141                    loc = installLocationPolicy(pkgLite);
15142                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15143                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15144                    } else if (!onSd && !onInt) {
15145                        // Override install location with flags
15146                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15147                            // Set the flag to install on external media.
15148                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15149                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15150                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15151                            if (DEBUG_INSTANT) {
15152                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15153                            }
15154                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15155                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15156                                    |PackageManager.INSTALL_INTERNAL);
15157                        } else {
15158                            // Make sure the flag for installing on external
15159                            // media is unset
15160                            installFlags |= PackageManager.INSTALL_INTERNAL;
15161                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15162                        }
15163                    }
15164                }
15165            }
15166
15167            final InstallArgs args = createInstallArgs(this);
15168            mArgs = args;
15169
15170            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15171                // TODO: http://b/22976637
15172                // Apps installed for "all" users use the device owner to verify the app
15173                UserHandle verifierUser = getUser();
15174                if (verifierUser == UserHandle.ALL) {
15175                    verifierUser = UserHandle.SYSTEM;
15176                }
15177
15178                /*
15179                 * Determine if we have any installed package verifiers. If we
15180                 * do, then we'll defer to them to verify the packages.
15181                 */
15182                final int requiredUid = mRequiredVerifierPackage == null ? -1
15183                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15184                                verifierUser.getIdentifier());
15185                final int installerUid =
15186                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15187                if (!origin.existing && requiredUid != -1
15188                        && isVerificationEnabled(
15189                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15190                    final Intent verification = new Intent(
15191                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15192                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15193                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15194                            PACKAGE_MIME_TYPE);
15195                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15196
15197                    // Query all live verifiers based on current user state
15198                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15199                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15200                            false /*allowDynamicSplits*/);
15201
15202                    if (DEBUG_VERIFY) {
15203                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15204                                + verification.toString() + " with " + pkgLite.verifiers.length
15205                                + " optional verifiers");
15206                    }
15207
15208                    final int verificationId = mPendingVerificationToken++;
15209
15210                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15211
15212                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15213                            installerPackageName);
15214
15215                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15216                            installFlags);
15217
15218                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15219                            pkgLite.packageName);
15220
15221                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15222                            pkgLite.versionCode);
15223
15224                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15225                            pkgLite.getLongVersionCode());
15226
15227                    if (verificationInfo != null) {
15228                        if (verificationInfo.originatingUri != null) {
15229                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15230                                    verificationInfo.originatingUri);
15231                        }
15232                        if (verificationInfo.referrer != null) {
15233                            verification.putExtra(Intent.EXTRA_REFERRER,
15234                                    verificationInfo.referrer);
15235                        }
15236                        if (verificationInfo.originatingUid >= 0) {
15237                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15238                                    verificationInfo.originatingUid);
15239                        }
15240                        if (verificationInfo.installerUid >= 0) {
15241                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15242                                    verificationInfo.installerUid);
15243                        }
15244                    }
15245
15246                    final PackageVerificationState verificationState = new PackageVerificationState(
15247                            requiredUid, args);
15248
15249                    mPendingVerification.append(verificationId, verificationState);
15250
15251                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15252                            receivers, verificationState);
15253
15254                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15255                    final long idleDuration = getVerificationTimeout();
15256
15257                    /*
15258                     * If any sufficient verifiers were listed in the package
15259                     * manifest, attempt to ask them.
15260                     */
15261                    if (sufficientVerifiers != null) {
15262                        final int N = sufficientVerifiers.size();
15263                        if (N == 0) {
15264                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15265                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15266                        } else {
15267                            for (int i = 0; i < N; i++) {
15268                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15269                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15270                                        verifierComponent.getPackageName(), idleDuration,
15271                                        verifierUser.getIdentifier(), false, "package verifier");
15272
15273                                final Intent sufficientIntent = new Intent(verification);
15274                                sufficientIntent.setComponent(verifierComponent);
15275                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15276                            }
15277                        }
15278                    }
15279
15280                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15281                            mRequiredVerifierPackage, receivers);
15282                    if (ret == PackageManager.INSTALL_SUCCEEDED
15283                            && mRequiredVerifierPackage != null) {
15284                        Trace.asyncTraceBegin(
15285                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15286                        /*
15287                         * Send the intent to the required verification agent,
15288                         * but only start the verification timeout after the
15289                         * target BroadcastReceivers have run.
15290                         */
15291                        verification.setComponent(requiredVerifierComponent);
15292                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15293                                mRequiredVerifierPackage, idleDuration,
15294                                verifierUser.getIdentifier(), false, "package verifier");
15295                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15296                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15297                                new BroadcastReceiver() {
15298                                    @Override
15299                                    public void onReceive(Context context, Intent intent) {
15300                                        final Message msg = mHandler
15301                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15302                                        msg.arg1 = verificationId;
15303                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15304                                    }
15305                                }, null, 0, null, null);
15306
15307                        /*
15308                         * We don't want the copy to proceed until verification
15309                         * succeeds, so null out this field.
15310                         */
15311                        mArgs = null;
15312                    }
15313                } else {
15314                    /*
15315                     * No package verification is enabled, so immediately start
15316                     * the remote call to initiate copy using temporary file.
15317                     */
15318                    ret = args.copyApk(mContainerService, true);
15319                }
15320            }
15321
15322            mRet = ret;
15323        }
15324
15325        @Override
15326        void handleReturnCode() {
15327            // If mArgs is null, then MCS couldn't be reached. When it
15328            // reconnects, it will try again to install. At that point, this
15329            // will succeed.
15330            if (mArgs != null) {
15331                processPendingInstall(mArgs, mRet);
15332            }
15333        }
15334
15335        @Override
15336        void handleServiceError() {
15337            mArgs = createInstallArgs(this);
15338            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15339        }
15340    }
15341
15342    private InstallArgs createInstallArgs(InstallParams params) {
15343        if (params.move != null) {
15344            return new MoveInstallArgs(params);
15345        } else {
15346            return new FileInstallArgs(params);
15347        }
15348    }
15349
15350    /**
15351     * Create args that describe an existing installed package. Typically used
15352     * when cleaning up old installs, or used as a move source.
15353     */
15354    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15355            String resourcePath, String[] instructionSets) {
15356        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15357    }
15358
15359    static abstract class InstallArgs {
15360        /** @see InstallParams#origin */
15361        final OriginInfo origin;
15362        /** @see InstallParams#move */
15363        final MoveInfo move;
15364
15365        final IPackageInstallObserver2 observer;
15366        // Always refers to PackageManager flags only
15367        final int installFlags;
15368        final String installerPackageName;
15369        final String volumeUuid;
15370        final UserHandle user;
15371        final String abiOverride;
15372        final String[] installGrantPermissions;
15373        /** If non-null, drop an async trace when the install completes */
15374        final String traceMethod;
15375        final int traceCookie;
15376        final PackageParser.SigningDetails signingDetails;
15377        final int installReason;
15378
15379        // The list of instruction sets supported by this app. This is currently
15380        // only used during the rmdex() phase to clean up resources. We can get rid of this
15381        // if we move dex files under the common app path.
15382        /* nullable */ String[] instructionSets;
15383
15384        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15385                int installFlags, String installerPackageName, String volumeUuid,
15386                UserHandle user, String[] instructionSets,
15387                String abiOverride, String[] installGrantPermissions,
15388                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15389                int installReason) {
15390            this.origin = origin;
15391            this.move = move;
15392            this.installFlags = installFlags;
15393            this.observer = observer;
15394            this.installerPackageName = installerPackageName;
15395            this.volumeUuid = volumeUuid;
15396            this.user = user;
15397            this.instructionSets = instructionSets;
15398            this.abiOverride = abiOverride;
15399            this.installGrantPermissions = installGrantPermissions;
15400            this.traceMethod = traceMethod;
15401            this.traceCookie = traceCookie;
15402            this.signingDetails = signingDetails;
15403            this.installReason = installReason;
15404        }
15405
15406        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15407        abstract int doPreInstall(int status);
15408
15409        /**
15410         * Rename package into final resting place. All paths on the given
15411         * scanned package should be updated to reflect the rename.
15412         */
15413        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15414        abstract int doPostInstall(int status, int uid);
15415
15416        /** @see PackageSettingBase#codePathString */
15417        abstract String getCodePath();
15418        /** @see PackageSettingBase#resourcePathString */
15419        abstract String getResourcePath();
15420
15421        // Need installer lock especially for dex file removal.
15422        abstract void cleanUpResourcesLI();
15423        abstract boolean doPostDeleteLI(boolean delete);
15424
15425        /**
15426         * Called before the source arguments are copied. This is used mostly
15427         * for MoveParams when it needs to read the source file to put it in the
15428         * destination.
15429         */
15430        int doPreCopy() {
15431            return PackageManager.INSTALL_SUCCEEDED;
15432        }
15433
15434        /**
15435         * Called after the source arguments are copied. This is used mostly for
15436         * MoveParams when it needs to read the source file to put it in the
15437         * destination.
15438         */
15439        int doPostCopy(int uid) {
15440            return PackageManager.INSTALL_SUCCEEDED;
15441        }
15442
15443        protected boolean isFwdLocked() {
15444            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15445        }
15446
15447        protected boolean isExternalAsec() {
15448            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15449        }
15450
15451        protected boolean isEphemeral() {
15452            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15453        }
15454
15455        UserHandle getUser() {
15456            return user;
15457        }
15458    }
15459
15460    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15461        if (!allCodePaths.isEmpty()) {
15462            if (instructionSets == null) {
15463                throw new IllegalStateException("instructionSet == null");
15464            }
15465            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15466            for (String codePath : allCodePaths) {
15467                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15468                    try {
15469                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15470                    } catch (InstallerException ignored) {
15471                    }
15472                }
15473            }
15474        }
15475    }
15476
15477    /**
15478     * Logic to handle installation of non-ASEC applications, including copying
15479     * and renaming logic.
15480     */
15481    class FileInstallArgs extends InstallArgs {
15482        private File codeFile;
15483        private File resourceFile;
15484
15485        // Example topology:
15486        // /data/app/com.example/base.apk
15487        // /data/app/com.example/split_foo.apk
15488        // /data/app/com.example/lib/arm/libfoo.so
15489        // /data/app/com.example/lib/arm64/libfoo.so
15490        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15491
15492        /** New install */
15493        FileInstallArgs(InstallParams params) {
15494            super(params.origin, params.move, params.observer, params.installFlags,
15495                    params.installerPackageName, params.volumeUuid,
15496                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15497                    params.grantedRuntimePermissions,
15498                    params.traceMethod, params.traceCookie, params.signingDetails,
15499                    params.installReason);
15500            if (isFwdLocked()) {
15501                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15502            }
15503        }
15504
15505        /** Existing install */
15506        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15507            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15508                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15509                    PackageManager.INSTALL_REASON_UNKNOWN);
15510            this.codeFile = (codePath != null) ? new File(codePath) : null;
15511            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15512        }
15513
15514        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15515            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15516            try {
15517                return doCopyApk(imcs, temp);
15518            } finally {
15519                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15520            }
15521        }
15522
15523        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15524            if (origin.staged) {
15525                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15526                codeFile = origin.file;
15527                resourceFile = origin.file;
15528                return PackageManager.INSTALL_SUCCEEDED;
15529            }
15530
15531            try {
15532                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15533                final File tempDir =
15534                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15535                codeFile = tempDir;
15536                resourceFile = tempDir;
15537            } catch (IOException e) {
15538                Slog.w(TAG, "Failed to create copy file: " + e);
15539                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15540            }
15541
15542            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15543                @Override
15544                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15545                    if (!FileUtils.isValidExtFilename(name)) {
15546                        throw new IllegalArgumentException("Invalid filename: " + name);
15547                    }
15548                    try {
15549                        final File file = new File(codeFile, name);
15550                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15551                                O_RDWR | O_CREAT, 0644);
15552                        Os.chmod(file.getAbsolutePath(), 0644);
15553                        return new ParcelFileDescriptor(fd);
15554                    } catch (ErrnoException e) {
15555                        throw new RemoteException("Failed to open: " + e.getMessage());
15556                    }
15557                }
15558            };
15559
15560            int ret = PackageManager.INSTALL_SUCCEEDED;
15561            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15562            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15563                Slog.e(TAG, "Failed to copy package");
15564                return ret;
15565            }
15566
15567            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15568            NativeLibraryHelper.Handle handle = null;
15569            try {
15570                handle = NativeLibraryHelper.Handle.create(codeFile);
15571                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15572                        abiOverride);
15573            } catch (IOException e) {
15574                Slog.e(TAG, "Copying native libraries failed", e);
15575                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15576            } finally {
15577                IoUtils.closeQuietly(handle);
15578            }
15579
15580            return ret;
15581        }
15582
15583        int doPreInstall(int status) {
15584            if (status != PackageManager.INSTALL_SUCCEEDED) {
15585                cleanUp();
15586            }
15587            return status;
15588        }
15589
15590        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15591            if (status != PackageManager.INSTALL_SUCCEEDED) {
15592                cleanUp();
15593                return false;
15594            }
15595
15596            final File targetDir = codeFile.getParentFile();
15597            final File beforeCodeFile = codeFile;
15598            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15599
15600            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15601            try {
15602                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15603            } catch (ErrnoException e) {
15604                Slog.w(TAG, "Failed to rename", e);
15605                return false;
15606            }
15607
15608            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15609                Slog.w(TAG, "Failed to restorecon");
15610                return false;
15611            }
15612
15613            // Reflect the rename internally
15614            codeFile = afterCodeFile;
15615            resourceFile = afterCodeFile;
15616
15617            // Reflect the rename in scanned details
15618            try {
15619                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15620            } catch (IOException e) {
15621                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15622                return false;
15623            }
15624            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15625                    afterCodeFile, pkg.baseCodePath));
15626            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15627                    afterCodeFile, pkg.splitCodePaths));
15628
15629            // Reflect the rename in app info
15630            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15631            pkg.setApplicationInfoCodePath(pkg.codePath);
15632            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15633            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15634            pkg.setApplicationInfoResourcePath(pkg.codePath);
15635            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15636            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15637
15638            return true;
15639        }
15640
15641        int doPostInstall(int status, int uid) {
15642            if (status != PackageManager.INSTALL_SUCCEEDED) {
15643                cleanUp();
15644            }
15645            return status;
15646        }
15647
15648        @Override
15649        String getCodePath() {
15650            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15651        }
15652
15653        @Override
15654        String getResourcePath() {
15655            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15656        }
15657
15658        private boolean cleanUp() {
15659            if (codeFile == null || !codeFile.exists()) {
15660                return false;
15661            }
15662
15663            removeCodePathLI(codeFile);
15664
15665            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15666                resourceFile.delete();
15667            }
15668
15669            return true;
15670        }
15671
15672        void cleanUpResourcesLI() {
15673            // Try enumerating all code paths before deleting
15674            List<String> allCodePaths = Collections.EMPTY_LIST;
15675            if (codeFile != null && codeFile.exists()) {
15676                try {
15677                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15678                    allCodePaths = pkg.getAllCodePaths();
15679                } catch (PackageParserException e) {
15680                    // Ignored; we tried our best
15681                }
15682            }
15683
15684            cleanUp();
15685            removeDexFiles(allCodePaths, instructionSets);
15686        }
15687
15688        boolean doPostDeleteLI(boolean delete) {
15689            // XXX err, shouldn't we respect the delete flag?
15690            cleanUpResourcesLI();
15691            return true;
15692        }
15693    }
15694
15695    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15696            PackageManagerException {
15697        if (copyRet < 0) {
15698            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15699                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15700                throw new PackageManagerException(copyRet, message);
15701            }
15702        }
15703    }
15704
15705    /**
15706     * Extract the StorageManagerService "container ID" from the full code path of an
15707     * .apk.
15708     */
15709    static String cidFromCodePath(String fullCodePath) {
15710        int eidx = fullCodePath.lastIndexOf("/");
15711        String subStr1 = fullCodePath.substring(0, eidx);
15712        int sidx = subStr1.lastIndexOf("/");
15713        return subStr1.substring(sidx+1, eidx);
15714    }
15715
15716    /**
15717     * Logic to handle movement of existing installed applications.
15718     */
15719    class MoveInstallArgs extends InstallArgs {
15720        private File codeFile;
15721        private File resourceFile;
15722
15723        /** New install */
15724        MoveInstallArgs(InstallParams params) {
15725            super(params.origin, params.move, params.observer, params.installFlags,
15726                    params.installerPackageName, params.volumeUuid,
15727                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15728                    params.grantedRuntimePermissions,
15729                    params.traceMethod, params.traceCookie, params.signingDetails,
15730                    params.installReason);
15731        }
15732
15733        int copyApk(IMediaContainerService imcs, boolean temp) {
15734            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15735                    + move.fromUuid + " to " + move.toUuid);
15736            synchronized (mInstaller) {
15737                try {
15738                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15739                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15740                } catch (InstallerException e) {
15741                    Slog.w(TAG, "Failed to move app", e);
15742                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15743                }
15744            }
15745
15746            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15747            resourceFile = codeFile;
15748            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15749
15750            return PackageManager.INSTALL_SUCCEEDED;
15751        }
15752
15753        int doPreInstall(int status) {
15754            if (status != PackageManager.INSTALL_SUCCEEDED) {
15755                cleanUp(move.toUuid);
15756            }
15757            return status;
15758        }
15759
15760        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15761            if (status != PackageManager.INSTALL_SUCCEEDED) {
15762                cleanUp(move.toUuid);
15763                return false;
15764            }
15765
15766            // Reflect the move in app info
15767            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15768            pkg.setApplicationInfoCodePath(pkg.codePath);
15769            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15770            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15771            pkg.setApplicationInfoResourcePath(pkg.codePath);
15772            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15773            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15774
15775            return true;
15776        }
15777
15778        int doPostInstall(int status, int uid) {
15779            if (status == PackageManager.INSTALL_SUCCEEDED) {
15780                cleanUp(move.fromUuid);
15781            } else {
15782                cleanUp(move.toUuid);
15783            }
15784            return status;
15785        }
15786
15787        @Override
15788        String getCodePath() {
15789            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15790        }
15791
15792        @Override
15793        String getResourcePath() {
15794            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15795        }
15796
15797        private boolean cleanUp(String volumeUuid) {
15798            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15799                    move.dataAppName);
15800            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15801            final int[] userIds = sUserManager.getUserIds();
15802            synchronized (mInstallLock) {
15803                // Clean up both app data and code
15804                // All package moves are frozen until finished
15805                for (int userId : userIds) {
15806                    try {
15807                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15808                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15809                    } catch (InstallerException e) {
15810                        Slog.w(TAG, String.valueOf(e));
15811                    }
15812                }
15813                removeCodePathLI(codeFile);
15814            }
15815            return true;
15816        }
15817
15818        void cleanUpResourcesLI() {
15819            throw new UnsupportedOperationException();
15820        }
15821
15822        boolean doPostDeleteLI(boolean delete) {
15823            throw new UnsupportedOperationException();
15824        }
15825    }
15826
15827    static String getAsecPackageName(String packageCid) {
15828        int idx = packageCid.lastIndexOf("-");
15829        if (idx == -1) {
15830            return packageCid;
15831        }
15832        return packageCid.substring(0, idx);
15833    }
15834
15835    // Utility method used to create code paths based on package name and available index.
15836    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15837        String idxStr = "";
15838        int idx = 1;
15839        // Fall back to default value of idx=1 if prefix is not
15840        // part of oldCodePath
15841        if (oldCodePath != null) {
15842            String subStr = oldCodePath;
15843            // Drop the suffix right away
15844            if (suffix != null && subStr.endsWith(suffix)) {
15845                subStr = subStr.substring(0, subStr.length() - suffix.length());
15846            }
15847            // If oldCodePath already contains prefix find out the
15848            // ending index to either increment or decrement.
15849            int sidx = subStr.lastIndexOf(prefix);
15850            if (sidx != -1) {
15851                subStr = subStr.substring(sidx + prefix.length());
15852                if (subStr != null) {
15853                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15854                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15855                    }
15856                    try {
15857                        idx = Integer.parseInt(subStr);
15858                        if (idx <= 1) {
15859                            idx++;
15860                        } else {
15861                            idx--;
15862                        }
15863                    } catch(NumberFormatException e) {
15864                    }
15865                }
15866            }
15867        }
15868        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15869        return prefix + idxStr;
15870    }
15871
15872    private File getNextCodePath(File targetDir, String packageName) {
15873        File result;
15874        SecureRandom random = new SecureRandom();
15875        byte[] bytes = new byte[16];
15876        do {
15877            random.nextBytes(bytes);
15878            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15879            result = new File(targetDir, packageName + "-" + suffix);
15880        } while (result.exists());
15881        return result;
15882    }
15883
15884    // Utility method that returns the relative package path with respect
15885    // to the installation directory. Like say for /data/data/com.test-1.apk
15886    // string com.test-1 is returned.
15887    static String deriveCodePathName(String codePath) {
15888        if (codePath == null) {
15889            return null;
15890        }
15891        final File codeFile = new File(codePath);
15892        final String name = codeFile.getName();
15893        if (codeFile.isDirectory()) {
15894            return name;
15895        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15896            final int lastDot = name.lastIndexOf('.');
15897            return name.substring(0, lastDot);
15898        } else {
15899            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15900            return null;
15901        }
15902    }
15903
15904    static class PackageInstalledInfo {
15905        String name;
15906        int uid;
15907        // The set of users that originally had this package installed.
15908        int[] origUsers;
15909        // The set of users that now have this package installed.
15910        int[] newUsers;
15911        PackageParser.Package pkg;
15912        int returnCode;
15913        String returnMsg;
15914        String installerPackageName;
15915        PackageRemovedInfo removedInfo;
15916        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15917
15918        public void setError(int code, String msg) {
15919            setReturnCode(code);
15920            setReturnMessage(msg);
15921            Slog.w(TAG, msg);
15922        }
15923
15924        public void setError(String msg, PackageParserException e) {
15925            setReturnCode(e.error);
15926            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15927            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15928            for (int i = 0; i < childCount; i++) {
15929                addedChildPackages.valueAt(i).setError(msg, e);
15930            }
15931            Slog.w(TAG, msg, e);
15932        }
15933
15934        public void setError(String msg, PackageManagerException e) {
15935            returnCode = e.error;
15936            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15937            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15938            for (int i = 0; i < childCount; i++) {
15939                addedChildPackages.valueAt(i).setError(msg, e);
15940            }
15941            Slog.w(TAG, msg, e);
15942        }
15943
15944        public void setReturnCode(int returnCode) {
15945            this.returnCode = returnCode;
15946            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15947            for (int i = 0; i < childCount; i++) {
15948                addedChildPackages.valueAt(i).returnCode = returnCode;
15949            }
15950        }
15951
15952        private void setReturnMessage(String returnMsg) {
15953            this.returnMsg = returnMsg;
15954            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15955            for (int i = 0; i < childCount; i++) {
15956                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15957            }
15958        }
15959
15960        // In some error cases we want to convey more info back to the observer
15961        String origPackage;
15962        String origPermission;
15963    }
15964
15965    /*
15966     * Install a non-existing package.
15967     */
15968    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15969            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15970            String volumeUuid, PackageInstalledInfo res, int installReason) {
15971        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15972
15973        // Remember this for later, in case we need to rollback this install
15974        String pkgName = pkg.packageName;
15975
15976        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15977
15978        synchronized(mPackages) {
15979            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15980            if (renamedPackage != null) {
15981                // A package with the same name is already installed, though
15982                // it has been renamed to an older name.  The package we
15983                // are trying to install should be installed as an update to
15984                // the existing one, but that has not been requested, so bail.
15985                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15986                        + " without first uninstalling package running as "
15987                        + renamedPackage);
15988                return;
15989            }
15990            if (mPackages.containsKey(pkgName)) {
15991                // Don't allow installation over an existing package with the same name.
15992                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15993                        + " without first uninstalling.");
15994                return;
15995            }
15996        }
15997
15998        try {
15999            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16000                    System.currentTimeMillis(), user);
16001
16002            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16003
16004            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16005                prepareAppDataAfterInstallLIF(newPackage);
16006
16007            } else {
16008                // Remove package from internal structures, but keep around any
16009                // data that might have already existed
16010                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16011                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16012            }
16013        } catch (PackageManagerException e) {
16014            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16015        }
16016
16017        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16018    }
16019
16020    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16021        try (DigestInputStream digestStream =
16022                new DigestInputStream(new FileInputStream(file), digest)) {
16023            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16024        }
16025    }
16026
16027    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16028            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16029            PackageInstalledInfo res, int installReason) {
16030        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16031
16032        final PackageParser.Package oldPackage;
16033        final PackageSetting ps;
16034        final String pkgName = pkg.packageName;
16035        final int[] allUsers;
16036        final int[] installedUsers;
16037
16038        synchronized(mPackages) {
16039            oldPackage = mPackages.get(pkgName);
16040            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16041
16042            // don't allow upgrade to target a release SDK from a pre-release SDK
16043            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16044                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16045            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16046                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16047            if (oldTargetsPreRelease
16048                    && !newTargetsPreRelease
16049                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16050                Slog.w(TAG, "Can't install package targeting released sdk");
16051                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16052                return;
16053            }
16054
16055            ps = mSettings.mPackages.get(pkgName);
16056
16057            // verify signatures are valid
16058            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16059            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16060                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16061                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16062                            "New package not signed by keys specified by upgrade-keysets: "
16063                                    + pkgName);
16064                    return;
16065                }
16066            } else {
16067
16068                // default to original signature matching
16069                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16070                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16071                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16072                            "New package has a different signature: " + pkgName);
16073                    return;
16074                }
16075            }
16076
16077            // don't allow a system upgrade unless the upgrade hash matches
16078            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16079                byte[] digestBytes = null;
16080                try {
16081                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16082                    updateDigest(digest, new File(pkg.baseCodePath));
16083                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16084                        for (String path : pkg.splitCodePaths) {
16085                            updateDigest(digest, new File(path));
16086                        }
16087                    }
16088                    digestBytes = digest.digest();
16089                } catch (NoSuchAlgorithmException | IOException e) {
16090                    res.setError(INSTALL_FAILED_INVALID_APK,
16091                            "Could not compute hash: " + pkgName);
16092                    return;
16093                }
16094                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16095                    res.setError(INSTALL_FAILED_INVALID_APK,
16096                            "New package fails restrict-update check: " + pkgName);
16097                    return;
16098                }
16099                // retain upgrade restriction
16100                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16101            }
16102
16103            // Check for shared user id changes
16104            String invalidPackageName =
16105                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16106            if (invalidPackageName != null) {
16107                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16108                        "Package " + invalidPackageName + " tried to change user "
16109                                + oldPackage.mSharedUserId);
16110                return;
16111            }
16112
16113            // check if the new package supports all of the abis which the old package supports
16114            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16115            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16116            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16117                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16118                        "Update to package " + pkgName + " doesn't support multi arch");
16119                return;
16120            }
16121
16122            // In case of rollback, remember per-user/profile install state
16123            allUsers = sUserManager.getUserIds();
16124            installedUsers = ps.queryInstalledUsers(allUsers, true);
16125
16126            // don't allow an upgrade from full to ephemeral
16127            if (isInstantApp) {
16128                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16129                    for (int currentUser : allUsers) {
16130                        if (!ps.getInstantApp(currentUser)) {
16131                            // can't downgrade from full to instant
16132                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16133                                    + " for user: " + currentUser);
16134                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16135                            return;
16136                        }
16137                    }
16138                } else if (!ps.getInstantApp(user.getIdentifier())) {
16139                    // can't downgrade from full to instant
16140                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16141                            + " for user: " + user.getIdentifier());
16142                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16143                    return;
16144                }
16145            }
16146        }
16147
16148        // Update what is removed
16149        res.removedInfo = new PackageRemovedInfo(this);
16150        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16151        res.removedInfo.removedPackage = oldPackage.packageName;
16152        res.removedInfo.installerPackageName = ps.installerPackageName;
16153        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16154        res.removedInfo.isUpdate = true;
16155        res.removedInfo.origUsers = installedUsers;
16156        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16157        for (int i = 0; i < installedUsers.length; i++) {
16158            final int userId = installedUsers[i];
16159            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16160        }
16161
16162        final int childCount = (oldPackage.childPackages != null)
16163                ? oldPackage.childPackages.size() : 0;
16164        for (int i = 0; i < childCount; i++) {
16165            boolean childPackageUpdated = false;
16166            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16167            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16168            if (res.addedChildPackages != null) {
16169                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16170                if (childRes != null) {
16171                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16172                    childRes.removedInfo.removedPackage = childPkg.packageName;
16173                    if (childPs != null) {
16174                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16175                    }
16176                    childRes.removedInfo.isUpdate = true;
16177                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16178                    childPackageUpdated = true;
16179                }
16180            }
16181            if (!childPackageUpdated) {
16182                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16183                childRemovedRes.removedPackage = childPkg.packageName;
16184                if (childPs != null) {
16185                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16186                }
16187                childRemovedRes.isUpdate = false;
16188                childRemovedRes.dataRemoved = true;
16189                synchronized (mPackages) {
16190                    if (childPs != null) {
16191                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16192                    }
16193                }
16194                if (res.removedInfo.removedChildPackages == null) {
16195                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16196                }
16197                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16198            }
16199        }
16200
16201        boolean sysPkg = (isSystemApp(oldPackage));
16202        if (sysPkg) {
16203            // Set the system/privileged/oem/vendor/product flags as needed
16204            final boolean privileged =
16205                    (oldPackage.applicationInfo.privateFlags
16206                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16207            final boolean oem =
16208                    (oldPackage.applicationInfo.privateFlags
16209                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16210            final boolean vendor =
16211                    (oldPackage.applicationInfo.privateFlags
16212                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16213            final boolean product =
16214                    (oldPackage.applicationInfo.privateFlags
16215                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16216            final @ParseFlags int systemParseFlags = parseFlags;
16217            final @ScanFlags int systemScanFlags = scanFlags
16218                    | SCAN_AS_SYSTEM
16219                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16220                    | (oem ? SCAN_AS_OEM : 0)
16221                    | (vendor ? SCAN_AS_VENDOR : 0)
16222                    | (product ? SCAN_AS_PRODUCT : 0);
16223
16224            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16225                    user, allUsers, installerPackageName, res, installReason);
16226        } else {
16227            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16228                    user, allUsers, installerPackageName, res, installReason);
16229        }
16230    }
16231
16232    @Override
16233    public List<String> getPreviousCodePaths(String packageName) {
16234        final int callingUid = Binder.getCallingUid();
16235        final List<String> result = new ArrayList<>();
16236        if (getInstantAppPackageName(callingUid) != null) {
16237            return result;
16238        }
16239        final PackageSetting ps = mSettings.mPackages.get(packageName);
16240        if (ps != null
16241                && ps.oldCodePaths != null
16242                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16243            result.addAll(ps.oldCodePaths);
16244        }
16245        return result;
16246    }
16247
16248    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16249            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16250            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16251            String installerPackageName, PackageInstalledInfo res, int installReason) {
16252        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16253                + deletedPackage);
16254
16255        String pkgName = deletedPackage.packageName;
16256        boolean deletedPkg = true;
16257        boolean addedPkg = false;
16258        boolean updatedSettings = false;
16259        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16260        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16261                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16262
16263        final long origUpdateTime = (pkg.mExtras != null)
16264                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16265
16266        // First delete the existing package while retaining the data directory
16267        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16268                res.removedInfo, true, pkg)) {
16269            // If the existing package wasn't successfully deleted
16270            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16271            deletedPkg = false;
16272        } else {
16273            // Successfully deleted the old package; proceed with replace.
16274
16275            // If deleted package lived in a container, give users a chance to
16276            // relinquish resources before killing.
16277            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16278                if (DEBUG_INSTALL) {
16279                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16280                }
16281                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16282                final ArrayList<String> pkgList = new ArrayList<String>(1);
16283                pkgList.add(deletedPackage.applicationInfo.packageName);
16284                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16285            }
16286
16287            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16288                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16289
16290            try {
16291                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16292                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16293                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16294                        installReason);
16295
16296                // Update the in-memory copy of the previous code paths.
16297                PackageSetting ps = mSettings.mPackages.get(pkgName);
16298                if (!killApp) {
16299                    if (ps.oldCodePaths == null) {
16300                        ps.oldCodePaths = new ArraySet<>();
16301                    }
16302                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16303                    if (deletedPackage.splitCodePaths != null) {
16304                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16305                    }
16306                } else {
16307                    ps.oldCodePaths = null;
16308                }
16309                if (ps.childPackageNames != null) {
16310                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16311                        final String childPkgName = ps.childPackageNames.get(i);
16312                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16313                        childPs.oldCodePaths = ps.oldCodePaths;
16314                    }
16315                }
16316                // set instant app status, but, only if it's explicitly specified
16317                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16318                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16319                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16320                prepareAppDataAfterInstallLIF(newPackage);
16321                addedPkg = true;
16322                mDexManager.notifyPackageUpdated(newPackage.packageName,
16323                        newPackage.baseCodePath, newPackage.splitCodePaths);
16324            } catch (PackageManagerException e) {
16325                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16326            }
16327        }
16328
16329        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16330            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16331
16332            // Revert all internal state mutations and added folders for the failed install
16333            if (addedPkg) {
16334                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16335                        res.removedInfo, true, null);
16336            }
16337
16338            // Restore the old package
16339            if (deletedPkg) {
16340                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16341                File restoreFile = new File(deletedPackage.codePath);
16342                // Parse old package
16343                boolean oldExternal = isExternal(deletedPackage);
16344                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16345                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16346                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16347                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16348                try {
16349                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16350                            null);
16351                } catch (PackageManagerException e) {
16352                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16353                            + e.getMessage());
16354                    return;
16355                }
16356
16357                synchronized (mPackages) {
16358                    // Ensure the installer package name up to date
16359                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16360
16361                    // Update permissions for restored package
16362                    mPermissionManager.updatePermissions(
16363                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16364                            mPermissionCallback);
16365
16366                    mSettings.writeLPr();
16367                }
16368
16369                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16370            }
16371        } else {
16372            synchronized (mPackages) {
16373                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16374                if (ps != null) {
16375                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16376                    if (res.removedInfo.removedChildPackages != null) {
16377                        final int childCount = res.removedInfo.removedChildPackages.size();
16378                        // Iterate in reverse as we may modify the collection
16379                        for (int i = childCount - 1; i >= 0; i--) {
16380                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16381                            if (res.addedChildPackages.containsKey(childPackageName)) {
16382                                res.removedInfo.removedChildPackages.removeAt(i);
16383                            } else {
16384                                PackageRemovedInfo childInfo = res.removedInfo
16385                                        .removedChildPackages.valueAt(i);
16386                                childInfo.removedForAllUsers = mPackages.get(
16387                                        childInfo.removedPackage) == null;
16388                            }
16389                        }
16390                    }
16391                }
16392            }
16393        }
16394    }
16395
16396    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16397            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16398            final @ScanFlags int scanFlags, UserHandle user,
16399            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16400            int installReason) {
16401        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16402                + ", old=" + deletedPackage);
16403
16404        final boolean disabledSystem;
16405
16406        // Remove existing system package
16407        removePackageLI(deletedPackage, true);
16408
16409        synchronized (mPackages) {
16410            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16411        }
16412        if (!disabledSystem) {
16413            // We didn't need to disable the .apk as a current system package,
16414            // which means we are replacing another update that is already
16415            // installed.  We need to make sure to delete the older one's .apk.
16416            res.removedInfo.args = createInstallArgsForExisting(0,
16417                    deletedPackage.applicationInfo.getCodePath(),
16418                    deletedPackage.applicationInfo.getResourcePath(),
16419                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16420        } else {
16421            res.removedInfo.args = null;
16422        }
16423
16424        // Successfully disabled the old package. Now proceed with re-installation
16425        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16426                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16427
16428        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16429        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16430                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16431
16432        PackageParser.Package newPackage = null;
16433        try {
16434            // Add the package to the internal data structures
16435            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16436
16437            // Set the update and install times
16438            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16439            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16440                    System.currentTimeMillis());
16441
16442            // Update the package dynamic state if succeeded
16443            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16444                // Now that the install succeeded make sure we remove data
16445                // directories for any child package the update removed.
16446                final int deletedChildCount = (deletedPackage.childPackages != null)
16447                        ? deletedPackage.childPackages.size() : 0;
16448                final int newChildCount = (newPackage.childPackages != null)
16449                        ? newPackage.childPackages.size() : 0;
16450                for (int i = 0; i < deletedChildCount; i++) {
16451                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16452                    boolean childPackageDeleted = true;
16453                    for (int j = 0; j < newChildCount; j++) {
16454                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16455                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16456                            childPackageDeleted = false;
16457                            break;
16458                        }
16459                    }
16460                    if (childPackageDeleted) {
16461                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16462                                deletedChildPkg.packageName);
16463                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16464                            PackageRemovedInfo removedChildRes = res.removedInfo
16465                                    .removedChildPackages.get(deletedChildPkg.packageName);
16466                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16467                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16468                        }
16469                    }
16470                }
16471
16472                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16473                        installReason);
16474                prepareAppDataAfterInstallLIF(newPackage);
16475
16476                mDexManager.notifyPackageUpdated(newPackage.packageName,
16477                            newPackage.baseCodePath, newPackage.splitCodePaths);
16478            }
16479        } catch (PackageManagerException e) {
16480            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16481            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16482        }
16483
16484        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16485            // Re installation failed. Restore old information
16486            // Remove new pkg information
16487            if (newPackage != null) {
16488                removeInstalledPackageLI(newPackage, true);
16489            }
16490            // Add back the old system package
16491            try {
16492                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16493            } catch (PackageManagerException e) {
16494                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16495            }
16496
16497            synchronized (mPackages) {
16498                if (disabledSystem) {
16499                    enableSystemPackageLPw(deletedPackage);
16500                }
16501
16502                // Ensure the installer package name up to date
16503                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16504
16505                // Update permissions for restored package
16506                mPermissionManager.updatePermissions(
16507                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16508                        mPermissionCallback);
16509
16510                mSettings.writeLPr();
16511            }
16512
16513            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16514                    + " after failed upgrade");
16515        }
16516    }
16517
16518    /**
16519     * Checks whether the parent or any of the child packages have a change shared
16520     * user. For a package to be a valid update the shred users of the parent and
16521     * the children should match. We may later support changing child shared users.
16522     * @param oldPkg The updated package.
16523     * @param newPkg The update package.
16524     * @return The shared user that change between the versions.
16525     */
16526    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16527            PackageParser.Package newPkg) {
16528        // Check parent shared user
16529        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16530            return newPkg.packageName;
16531        }
16532        // Check child shared users
16533        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16534        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16535        for (int i = 0; i < newChildCount; i++) {
16536            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16537            // If this child was present, did it have the same shared user?
16538            for (int j = 0; j < oldChildCount; j++) {
16539                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16540                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16541                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16542                    return newChildPkg.packageName;
16543                }
16544            }
16545        }
16546        return null;
16547    }
16548
16549    private void removeNativeBinariesLI(PackageSetting ps) {
16550        // Remove the lib path for the parent package
16551        if (ps != null) {
16552            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16553            // Remove the lib path for the child packages
16554            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16555            for (int i = 0; i < childCount; i++) {
16556                PackageSetting childPs = null;
16557                synchronized (mPackages) {
16558                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16559                }
16560                if (childPs != null) {
16561                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16562                            .legacyNativeLibraryPathString);
16563                }
16564            }
16565        }
16566    }
16567
16568    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16569        // Enable the parent package
16570        mSettings.enableSystemPackageLPw(pkg.packageName);
16571        // Enable the child packages
16572        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16573        for (int i = 0; i < childCount; i++) {
16574            PackageParser.Package childPkg = pkg.childPackages.get(i);
16575            mSettings.enableSystemPackageLPw(childPkg.packageName);
16576        }
16577    }
16578
16579    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16580            PackageParser.Package newPkg) {
16581        // Disable the parent package (parent always replaced)
16582        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16583        // Disable the child packages
16584        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16585        for (int i = 0; i < childCount; i++) {
16586            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16587            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16588            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16589        }
16590        return disabled;
16591    }
16592
16593    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16594            String installerPackageName) {
16595        // Enable the parent package
16596        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16597        // Enable the child packages
16598        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16599        for (int i = 0; i < childCount; i++) {
16600            PackageParser.Package childPkg = pkg.childPackages.get(i);
16601            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16602        }
16603    }
16604
16605    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16606            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16607        // Update the parent package setting
16608        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16609                res, user, installReason);
16610        // Update the child packages setting
16611        final int childCount = (newPackage.childPackages != null)
16612                ? newPackage.childPackages.size() : 0;
16613        for (int i = 0; i < childCount; i++) {
16614            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16615            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16616            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16617                    childRes.origUsers, childRes, user, installReason);
16618        }
16619    }
16620
16621    private void updateSettingsInternalLI(PackageParser.Package pkg,
16622            String installerPackageName, int[] allUsers, int[] installedForUsers,
16623            PackageInstalledInfo res, UserHandle user, int installReason) {
16624        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16625
16626        final String pkgName = pkg.packageName;
16627
16628        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16629        synchronized (mPackages) {
16630// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16631            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16632                    mPermissionCallback);
16633            // For system-bundled packages, we assume that installing an upgraded version
16634            // of the package implies that the user actually wants to run that new code,
16635            // so we enable the package.
16636            PackageSetting ps = mSettings.mPackages.get(pkgName);
16637            final int userId = user.getIdentifier();
16638            if (ps != null) {
16639                if (isSystemApp(pkg)) {
16640                    if (DEBUG_INSTALL) {
16641                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16642                    }
16643                    // Enable system package for requested users
16644                    if (res.origUsers != null) {
16645                        for (int origUserId : res.origUsers) {
16646                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16647                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16648                                        origUserId, installerPackageName);
16649                            }
16650                        }
16651                    }
16652                    // Also convey the prior install/uninstall state
16653                    if (allUsers != null && installedForUsers != null) {
16654                        for (int currentUserId : allUsers) {
16655                            final boolean installed = ArrayUtils.contains(
16656                                    installedForUsers, currentUserId);
16657                            if (DEBUG_INSTALL) {
16658                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16659                            }
16660                            ps.setInstalled(installed, currentUserId);
16661                        }
16662                        // these install state changes will be persisted in the
16663                        // upcoming call to mSettings.writeLPr().
16664                    }
16665                }
16666                // It's implied that when a user requests installation, they want the app to be
16667                // installed and enabled.
16668                if (userId != UserHandle.USER_ALL) {
16669                    ps.setInstalled(true, userId);
16670                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16671                } else {
16672                    for (int currentUserId : sUserManager.getUserIds()) {
16673                        ps.setInstalled(true, currentUserId);
16674                        ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId,
16675                                installerPackageName);
16676                    }
16677                }
16678
16679                // When replacing an existing package, preserve the original install reason for all
16680                // users that had the package installed before.
16681                final Set<Integer> previousUserIds = new ArraySet<>();
16682                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16683                    final int installReasonCount = res.removedInfo.installReasons.size();
16684                    for (int i = 0; i < installReasonCount; i++) {
16685                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16686                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16687                        ps.setInstallReason(previousInstallReason, previousUserId);
16688                        previousUserIds.add(previousUserId);
16689                    }
16690                }
16691
16692                // Set install reason for users that are having the package newly installed.
16693                if (userId == UserHandle.USER_ALL) {
16694                    for (int currentUserId : sUserManager.getUserIds()) {
16695                        if (!previousUserIds.contains(currentUserId)) {
16696                            ps.setInstallReason(installReason, currentUserId);
16697                        }
16698                    }
16699                } else if (!previousUserIds.contains(userId)) {
16700                    ps.setInstallReason(installReason, userId);
16701                }
16702                mSettings.writeKernelMappingLPr(ps);
16703            }
16704            res.name = pkgName;
16705            res.uid = pkg.applicationInfo.uid;
16706            res.pkg = pkg;
16707            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16708            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16709            //to update install status
16710            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16711            mSettings.writeLPr();
16712            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16713        }
16714
16715        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16716    }
16717
16718    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16719        try {
16720            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16721            installPackageLI(args, res);
16722        } finally {
16723            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16724        }
16725    }
16726
16727    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16728        final int installFlags = args.installFlags;
16729        final String installerPackageName = args.installerPackageName;
16730        final String volumeUuid = args.volumeUuid;
16731        final File tmpPackageFile = new File(args.getCodePath());
16732        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16733        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16734                || (args.volumeUuid != null));
16735        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16736        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16737        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16738        final boolean virtualPreload =
16739                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16740        boolean replace = false;
16741        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16742        if (args.move != null) {
16743            // moving a complete application; perform an initial scan on the new install location
16744            scanFlags |= SCAN_INITIAL;
16745        }
16746        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16747            scanFlags |= SCAN_DONT_KILL_APP;
16748        }
16749        if (instantApp) {
16750            scanFlags |= SCAN_AS_INSTANT_APP;
16751        }
16752        if (fullApp) {
16753            scanFlags |= SCAN_AS_FULL_APP;
16754        }
16755        if (virtualPreload) {
16756            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16757        }
16758
16759        // Result object to be returned
16760        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16761        res.installerPackageName = installerPackageName;
16762
16763        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16764
16765        // Sanity check
16766        if (instantApp && (forwardLocked || onExternal)) {
16767            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16768                    + " external=" + onExternal);
16769            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16770            return;
16771        }
16772
16773        // Retrieve PackageSettings and parse package
16774        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16775                | PackageParser.PARSE_ENFORCE_CODE
16776                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16777                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16778                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16779        PackageParser pp = new PackageParser();
16780        pp.setSeparateProcesses(mSeparateProcesses);
16781        pp.setDisplayMetrics(mMetrics);
16782        pp.setCallback(mPackageParserCallback);
16783
16784        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16785        final PackageParser.Package pkg;
16786        try {
16787            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16788            DexMetadataHelper.validatePackageDexMetadata(pkg);
16789        } catch (PackageParserException e) {
16790            res.setError("Failed parse during installPackageLI", e);
16791            return;
16792        } finally {
16793            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16794        }
16795
16796        // Instant apps have several additional install-time checks.
16797        if (instantApp) {
16798            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16799                Slog.w(TAG,
16800                        "Instant app package " + pkg.packageName + " does not target at least O");
16801                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16802                        "Instant app package must target at least O");
16803                return;
16804            }
16805            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16806                Slog.w(TAG, "Instant app package " + pkg.packageName
16807                        + " does not target targetSandboxVersion 2");
16808                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16809                        "Instant app package must use targetSandboxVersion 2");
16810                return;
16811            }
16812            if (pkg.mSharedUserId != null) {
16813                Slog.w(TAG, "Instant app package " + pkg.packageName
16814                        + " may not declare sharedUserId.");
16815                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16816                        "Instant app package may not declare a sharedUserId");
16817                return;
16818            }
16819        }
16820
16821        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16822            // Static shared libraries have synthetic package names
16823            renameStaticSharedLibraryPackage(pkg);
16824
16825            // No static shared libs on external storage
16826            if (onExternal) {
16827                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16828                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16829                        "Packages declaring static-shared libs cannot be updated");
16830                return;
16831            }
16832        }
16833
16834        // If we are installing a clustered package add results for the children
16835        if (pkg.childPackages != null) {
16836            synchronized (mPackages) {
16837                final int childCount = pkg.childPackages.size();
16838                for (int i = 0; i < childCount; i++) {
16839                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16840                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16841                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16842                    childRes.pkg = childPkg;
16843                    childRes.name = childPkg.packageName;
16844                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16845                    if (childPs != null) {
16846                        childRes.origUsers = childPs.queryInstalledUsers(
16847                                sUserManager.getUserIds(), true);
16848                    }
16849                    if ((mPackages.containsKey(childPkg.packageName))) {
16850                        childRes.removedInfo = new PackageRemovedInfo(this);
16851                        childRes.removedInfo.removedPackage = childPkg.packageName;
16852                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16853                    }
16854                    if (res.addedChildPackages == null) {
16855                        res.addedChildPackages = new ArrayMap<>();
16856                    }
16857                    res.addedChildPackages.put(childPkg.packageName, childRes);
16858                }
16859            }
16860        }
16861
16862        // If package doesn't declare API override, mark that we have an install
16863        // time CPU ABI override.
16864        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16865            pkg.cpuAbiOverride = args.abiOverride;
16866        }
16867
16868        String pkgName = res.name = pkg.packageName;
16869        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16870            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16871                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16872                return;
16873            }
16874        }
16875
16876        try {
16877            // either use what we've been given or parse directly from the APK
16878            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16879                pkg.setSigningDetails(args.signingDetails);
16880            } else {
16881                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16882            }
16883        } catch (PackageParserException e) {
16884            res.setError("Failed collect during installPackageLI", e);
16885            return;
16886        }
16887
16888        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16889                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16890            Slog.w(TAG, "Instant app package " + pkg.packageName
16891                    + " is not signed with at least APK Signature Scheme v2");
16892            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16893                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16894            return;
16895        }
16896
16897        // Get rid of all references to package scan path via parser.
16898        pp = null;
16899        String oldCodePath = null;
16900        boolean systemApp = false;
16901        synchronized (mPackages) {
16902            // Check if installing already existing package
16903            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16904                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16905                if (pkg.mOriginalPackages != null
16906                        && pkg.mOriginalPackages.contains(oldName)
16907                        && mPackages.containsKey(oldName)) {
16908                    // This package is derived from an original package,
16909                    // and this device has been updating from that original
16910                    // name.  We must continue using the original name, so
16911                    // rename the new package here.
16912                    pkg.setPackageName(oldName);
16913                    pkgName = pkg.packageName;
16914                    replace = true;
16915                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16916                            + oldName + " pkgName=" + pkgName);
16917                } else if (mPackages.containsKey(pkgName)) {
16918                    // This package, under its official name, already exists
16919                    // on the device; we should replace it.
16920                    replace = true;
16921                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16922                }
16923
16924                // Child packages are installed through the parent package
16925                if (pkg.parentPackage != null) {
16926                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16927                            "Package " + pkg.packageName + " is child of package "
16928                                    + pkg.parentPackage.parentPackage + ". Child packages "
16929                                    + "can be updated only through the parent package.");
16930                    return;
16931                }
16932
16933                if (replace) {
16934                    // Prevent apps opting out from runtime permissions
16935                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16936                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16937                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16938                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16939                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16940                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16941                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16942                                        + " doesn't support runtime permissions but the old"
16943                                        + " target SDK " + oldTargetSdk + " does.");
16944                        return;
16945                    }
16946                    // Prevent persistent apps from being updated
16947                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16948                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16949                                "Package " + oldPackage.packageName + " is a persistent app. "
16950                                        + "Persistent apps are not updateable.");
16951                        return;
16952                    }
16953                    // Prevent apps from downgrading their targetSandbox.
16954                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16955                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16956                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16957                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16958                                "Package " + pkg.packageName + " new target sandbox "
16959                                + newTargetSandbox + " is incompatible with the previous value of"
16960                                + oldTargetSandbox + ".");
16961                        return;
16962                    }
16963
16964                    // Prevent installing of child packages
16965                    if (oldPackage.parentPackage != null) {
16966                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16967                                "Package " + pkg.packageName + " is child of package "
16968                                        + oldPackage.parentPackage + ". Child packages "
16969                                        + "can be updated only through the parent package.");
16970                        return;
16971                    }
16972                }
16973            }
16974
16975            PackageSetting ps = mSettings.mPackages.get(pkgName);
16976            if (ps != null) {
16977                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16978
16979                // Static shared libs have same package with different versions where
16980                // we internally use a synthetic package name to allow multiple versions
16981                // of the same package, therefore we need to compare signatures against
16982                // the package setting for the latest library version.
16983                PackageSetting signatureCheckPs = ps;
16984                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16985                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16986                    if (libraryEntry != null) {
16987                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16988                    }
16989                }
16990
16991                // Quick sanity check that we're signed correctly if updating;
16992                // we'll check this again later when scanning, but we want to
16993                // bail early here before tripping over redefined permissions.
16994                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16995                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16996                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16997                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16998                                + pkg.packageName + " upgrade keys do not match the "
16999                                + "previously installed version");
17000                        return;
17001                    }
17002                } else {
17003                    try {
17004                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17005                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17006                        // We don't care about disabledPkgSetting on install for now.
17007                        final boolean compatMatch = verifySignatures(
17008                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17009                                compareRecover);
17010                        // The new KeySets will be re-added later in the scanning process.
17011                        if (compatMatch) {
17012                            synchronized (mPackages) {
17013                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17014                            }
17015                        }
17016                    } catch (PackageManagerException e) {
17017                        res.setError(e.error, e.getMessage());
17018                        return;
17019                    }
17020                }
17021
17022                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17023                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17024                    systemApp = (ps.pkg.applicationInfo.flags &
17025                            ApplicationInfo.FLAG_SYSTEM) != 0;
17026                }
17027                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17028            }
17029
17030            int N = pkg.permissions.size();
17031            for (int i = N-1; i >= 0; i--) {
17032                final PackageParser.Permission perm = pkg.permissions.get(i);
17033                final BasePermission bp =
17034                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17035
17036                // Don't allow anyone but the system to define ephemeral permissions.
17037                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17038                        && !systemApp) {
17039                    Slog.w(TAG, "Non-System package " + pkg.packageName
17040                            + " attempting to delcare ephemeral permission "
17041                            + perm.info.name + "; Removing ephemeral.");
17042                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17043                }
17044
17045                // Check whether the newly-scanned package wants to define an already-defined perm
17046                if (bp != null) {
17047                    // If the defining package is signed with our cert, it's okay.  This
17048                    // also includes the "updating the same package" case, of course.
17049                    // "updating same package" could also involve key-rotation.
17050                    final boolean sigsOk;
17051                    final String sourcePackageName = bp.getSourcePackageName();
17052                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17053                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17054                    if (sourcePackageName.equals(pkg.packageName)
17055                            && (ksms.shouldCheckUpgradeKeySetLocked(
17056                                    sourcePackageSetting, scanFlags))) {
17057                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17058                    } else {
17059
17060                        // in the event of signing certificate rotation, we need to see if the
17061                        // package's certificate has rotated from the current one, or if it is an
17062                        // older certificate with which the current is ok with sharing permissions
17063                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17064                                        pkg.mSigningDetails,
17065                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17066                            sigsOk = true;
17067                        } else if (pkg.mSigningDetails.checkCapability(
17068                                        sourcePackageSetting.signatures.mSigningDetails,
17069                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17070
17071                            // the scanned package checks out, has signing certificate rotation
17072                            // history, and is newer; bring it over
17073                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17074                            sigsOk = true;
17075                        } else {
17076                            sigsOk = false;
17077                        }
17078                    }
17079                    if (!sigsOk) {
17080                        // If the owning package is the system itself, we log but allow
17081                        // install to proceed; we fail the install on all other permission
17082                        // redefinitions.
17083                        if (!sourcePackageName.equals("android")) {
17084                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17085                                    + pkg.packageName + " attempting to redeclare permission "
17086                                    + perm.info.name + " already owned by " + sourcePackageName);
17087                            res.origPermission = perm.info.name;
17088                            res.origPackage = sourcePackageName;
17089                            return;
17090                        } else {
17091                            Slog.w(TAG, "Package " + pkg.packageName
17092                                    + " attempting to redeclare system permission "
17093                                    + perm.info.name + "; ignoring new declaration");
17094                            pkg.permissions.remove(i);
17095                        }
17096                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17097                        // Prevent apps to change protection level to dangerous from any other
17098                        // type as this would allow a privilege escalation where an app adds a
17099                        // normal/signature permission in other app's group and later redefines
17100                        // it as dangerous leading to the group auto-grant.
17101                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17102                                == PermissionInfo.PROTECTION_DANGEROUS) {
17103                            if (bp != null && !bp.isRuntime()) {
17104                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17105                                        + "non-runtime permission " + perm.info.name
17106                                        + " to runtime; keeping old protection level");
17107                                perm.info.protectionLevel = bp.getProtectionLevel();
17108                            }
17109                        }
17110                    }
17111                }
17112            }
17113        }
17114
17115        if (systemApp) {
17116            if (onExternal) {
17117                // Abort update; system app can't be replaced with app on sdcard
17118                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17119                        "Cannot install updates to system apps on sdcard");
17120                return;
17121            } else if (instantApp) {
17122                // Abort update; system app can't be replaced with an instant app
17123                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17124                        "Cannot update a system app with an instant app");
17125                return;
17126            }
17127        }
17128
17129        if (args.move != null) {
17130            // We did an in-place move, so dex is ready to roll
17131            scanFlags |= SCAN_NO_DEX;
17132            scanFlags |= SCAN_MOVE;
17133
17134            synchronized (mPackages) {
17135                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17136                if (ps == null) {
17137                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17138                            "Missing settings for moved package " + pkgName);
17139                }
17140
17141                // We moved the entire application as-is, so bring over the
17142                // previously derived ABI information.
17143                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17144                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17145            }
17146
17147        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17148            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17149            scanFlags |= SCAN_NO_DEX;
17150
17151            try {
17152                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17153                    args.abiOverride : pkg.cpuAbiOverride);
17154                final boolean extractNativeLibs = !pkg.isLibrary();
17155                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17156            } catch (PackageManagerException pme) {
17157                Slog.e(TAG, "Error deriving application ABI", pme);
17158                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17159                return;
17160            }
17161
17162            // Shared libraries for the package need to be updated.
17163            synchronized (mPackages) {
17164                try {
17165                    updateSharedLibrariesLPr(pkg, null);
17166                } catch (PackageManagerException e) {
17167                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17168                }
17169            }
17170        }
17171
17172        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17173            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17174            return;
17175        }
17176
17177        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17178            String apkPath = null;
17179            synchronized (mPackages) {
17180                // Note that if the attacker managed to skip verify setup, for example by tampering
17181                // with the package settings, upon reboot we will do full apk verification when
17182                // verity is not detected.
17183                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17184                if (ps != null && ps.isPrivileged()) {
17185                    apkPath = pkg.baseCodePath;
17186                }
17187            }
17188
17189            if (apkPath != null) {
17190                final VerityUtils.SetupResult result =
17191                        VerityUtils.generateApkVeritySetupData(apkPath);
17192                if (result.isOk()) {
17193                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17194                    FileDescriptor fd = result.getUnownedFileDescriptor();
17195                    try {
17196                        mInstaller.installApkVerity(apkPath, fd);
17197                    } catch (InstallerException e) {
17198                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17199                                "Failed to set up verity: " + e);
17200                        return;
17201                    } finally {
17202                        IoUtils.closeQuietly(fd);
17203                    }
17204                } else if (result.isFailed()) {
17205                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17206                    return;
17207                } else {
17208                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17209                    // reboot.
17210                }
17211            }
17212        }
17213
17214        if (!instantApp) {
17215            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17216        } else {
17217            if (DEBUG_DOMAIN_VERIFICATION) {
17218                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17219            }
17220        }
17221
17222        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17223                "installPackageLI")) {
17224            if (replace) {
17225                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17226                    // Static libs have a synthetic package name containing the version
17227                    // and cannot be updated as an update would get a new package name,
17228                    // unless this is the exact same version code which is useful for
17229                    // development.
17230                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17231                    if (existingPkg != null &&
17232                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17233                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17234                                + "static-shared libs cannot be updated");
17235                        return;
17236                    }
17237                }
17238                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17239                        installerPackageName, res, args.installReason);
17240            } else {
17241                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17242                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17243            }
17244        }
17245
17246        // Prepare the application profiles for the new code paths.
17247        // This needs to be done before invoking dexopt so that any install-time profile
17248        // can be used for optimizations.
17249        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17250
17251        // Check whether we need to dexopt the app.
17252        //
17253        // NOTE: it is IMPORTANT to call dexopt:
17254        //   - after doRename which will sync the package data from PackageParser.Package and its
17255        //     corresponding ApplicationInfo.
17256        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17257        //     uid of the application (pkg.applicationInfo.uid).
17258        //     This update happens in place!
17259        //
17260        // We only need to dexopt if the package meets ALL of the following conditions:
17261        //   1) it is not forward locked.
17262        //   2) it is not on on an external ASEC container.
17263        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17264        //
17265        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17266        // complete, so we skip this step during installation. Instead, we'll take extra time
17267        // the first time the instant app starts. It's preferred to do it this way to provide
17268        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17269        // middle of running an instant app. The default behaviour can be overridden
17270        // via gservices.
17271        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17272                && !forwardLocked
17273                && !pkg.applicationInfo.isExternalAsec()
17274                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17275                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17276
17277        if (performDexopt) {
17278            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17279            // Do not run PackageDexOptimizer through the local performDexOpt
17280            // method because `pkg` may not be in `mPackages` yet.
17281            //
17282            // Also, don't fail application installs if the dexopt step fails.
17283            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17284                    REASON_INSTALL,
17285                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17286                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17287            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17288                    null /* instructionSets */,
17289                    getOrCreateCompilerPackageStats(pkg),
17290                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17291                    dexoptOptions);
17292            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17293        }
17294
17295        // Notify BackgroundDexOptService that the package has been changed.
17296        // If this is an update of a package which used to fail to compile,
17297        // BackgroundDexOptService will remove it from its blacklist.
17298        // TODO: Layering violation
17299        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17300
17301        synchronized (mPackages) {
17302            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17303            if (ps != null) {
17304                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17305                ps.setUpdateAvailable(false /*updateAvailable*/);
17306            }
17307
17308            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17309            for (int i = 0; i < childCount; i++) {
17310                PackageParser.Package childPkg = pkg.childPackages.get(i);
17311                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17312                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17313                if (childPs != null) {
17314                    childRes.newUsers = childPs.queryInstalledUsers(
17315                            sUserManager.getUserIds(), true);
17316                }
17317            }
17318
17319            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17320                updateSequenceNumberLP(ps, res.newUsers);
17321                updateInstantAppInstallerLocked(pkgName);
17322            }
17323        }
17324    }
17325
17326    private void startIntentFilterVerifications(int userId, boolean replacing,
17327            PackageParser.Package pkg) {
17328        if (mIntentFilterVerifierComponent == null) {
17329            Slog.w(TAG, "No IntentFilter verification will not be done as "
17330                    + "there is no IntentFilterVerifier available!");
17331            return;
17332        }
17333
17334        final int verifierUid = getPackageUid(
17335                mIntentFilterVerifierComponent.getPackageName(),
17336                MATCH_DEBUG_TRIAGED_MISSING,
17337                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17338
17339        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17340        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17341        mHandler.sendMessage(msg);
17342
17343        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17344        for (int i = 0; i < childCount; i++) {
17345            PackageParser.Package childPkg = pkg.childPackages.get(i);
17346            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17347            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17348            mHandler.sendMessage(msg);
17349        }
17350    }
17351
17352    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17353            PackageParser.Package pkg) {
17354        int size = pkg.activities.size();
17355        if (size == 0) {
17356            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17357                    "No activity, so no need to verify any IntentFilter!");
17358            return;
17359        }
17360
17361        final boolean hasDomainURLs = hasDomainURLs(pkg);
17362        if (!hasDomainURLs) {
17363            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17364                    "No domain URLs, so no need to verify any IntentFilter!");
17365            return;
17366        }
17367
17368        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17369                + " if any IntentFilter from the " + size
17370                + " Activities needs verification ...");
17371
17372        int count = 0;
17373        final String packageName = pkg.packageName;
17374
17375        synchronized (mPackages) {
17376            // If this is a new install and we see that we've already run verification for this
17377            // package, we have nothing to do: it means the state was restored from backup.
17378            if (!replacing) {
17379                IntentFilterVerificationInfo ivi =
17380                        mSettings.getIntentFilterVerificationLPr(packageName);
17381                if (ivi != null) {
17382                    if (DEBUG_DOMAIN_VERIFICATION) {
17383                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17384                                + ivi.getStatusString());
17385                    }
17386                    return;
17387                }
17388            }
17389
17390            // If any filters need to be verified, then all need to be.
17391            boolean needToVerify = false;
17392            for (PackageParser.Activity a : pkg.activities) {
17393                for (ActivityIntentInfo filter : a.intents) {
17394                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17395                        if (DEBUG_DOMAIN_VERIFICATION) {
17396                            Slog.d(TAG,
17397                                    "Intent filter needs verification, so processing all filters");
17398                        }
17399                        needToVerify = true;
17400                        break;
17401                    }
17402                }
17403            }
17404
17405            if (needToVerify) {
17406                final int verificationId = mIntentFilterVerificationToken++;
17407                for (PackageParser.Activity a : pkg.activities) {
17408                    for (ActivityIntentInfo filter : a.intents) {
17409                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17410                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17411                                    "Verification needed for IntentFilter:" + filter.toString());
17412                            mIntentFilterVerifier.addOneIntentFilterVerification(
17413                                    verifierUid, userId, verificationId, filter, packageName);
17414                            count++;
17415                        }
17416                    }
17417                }
17418            }
17419        }
17420
17421        if (count > 0) {
17422            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17423                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17424                    +  " for userId:" + userId);
17425            mIntentFilterVerifier.startVerifications(userId);
17426        } else {
17427            if (DEBUG_DOMAIN_VERIFICATION) {
17428                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17429            }
17430        }
17431    }
17432
17433    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17434        final ComponentName cn  = filter.activity.getComponentName();
17435        final String packageName = cn.getPackageName();
17436
17437        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17438                packageName);
17439        if (ivi == null) {
17440            return true;
17441        }
17442        int status = ivi.getStatus();
17443        switch (status) {
17444            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17445            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17446                return true;
17447
17448            default:
17449                // Nothing to do
17450                return false;
17451        }
17452    }
17453
17454    private static boolean isMultiArch(ApplicationInfo info) {
17455        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17456    }
17457
17458    private static boolean isExternal(PackageParser.Package pkg) {
17459        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17460    }
17461
17462    private static boolean isExternal(PackageSetting ps) {
17463        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17464    }
17465
17466    private static boolean isSystemApp(PackageParser.Package pkg) {
17467        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17468    }
17469
17470    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17471        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17472    }
17473
17474    private static boolean isOemApp(PackageParser.Package pkg) {
17475        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17476    }
17477
17478    private static boolean isVendorApp(PackageParser.Package pkg) {
17479        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17480    }
17481
17482    private static boolean isProductApp(PackageParser.Package pkg) {
17483        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17484    }
17485
17486    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17487        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17488    }
17489
17490    private static boolean isSystemApp(PackageSetting ps) {
17491        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17492    }
17493
17494    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17495        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17496    }
17497
17498    private int packageFlagsToInstallFlags(PackageSetting ps) {
17499        int installFlags = 0;
17500        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17501            // This existing package was an external ASEC install when we have
17502            // the external flag without a UUID
17503            installFlags |= PackageManager.INSTALL_EXTERNAL;
17504        }
17505        if (ps.isForwardLocked()) {
17506            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17507        }
17508        return installFlags;
17509    }
17510
17511    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17512        if (isExternal(pkg)) {
17513            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17514                return mSettings.getExternalVersion();
17515            } else {
17516                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17517            }
17518        } else {
17519            return mSettings.getInternalVersion();
17520        }
17521    }
17522
17523    private void deleteTempPackageFiles() {
17524        final FilenameFilter filter = new FilenameFilter() {
17525            public boolean accept(File dir, String name) {
17526                return name.startsWith("vmdl") && name.endsWith(".tmp");
17527            }
17528        };
17529        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17530            file.delete();
17531        }
17532    }
17533
17534    @Override
17535    public void deletePackageAsUser(String packageName, int versionCode,
17536            IPackageDeleteObserver observer, int userId, int flags) {
17537        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17538                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17539    }
17540
17541    @Override
17542    public void deletePackageVersioned(VersionedPackage versionedPackage,
17543            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17544        final int callingUid = Binder.getCallingUid();
17545        mContext.enforceCallingOrSelfPermission(
17546                android.Manifest.permission.DELETE_PACKAGES, null);
17547        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17548        Preconditions.checkNotNull(versionedPackage);
17549        Preconditions.checkNotNull(observer);
17550        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17551                PackageManager.VERSION_CODE_HIGHEST,
17552                Long.MAX_VALUE, "versionCode must be >= -1");
17553
17554        final String packageName = versionedPackage.getPackageName();
17555        final long versionCode = versionedPackage.getLongVersionCode();
17556        final String internalPackageName;
17557        synchronized (mPackages) {
17558            // Normalize package name to handle renamed packages and static libs
17559            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17560        }
17561
17562        final int uid = Binder.getCallingUid();
17563        if (!isOrphaned(internalPackageName)
17564                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17565            try {
17566                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17567                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17568                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17569                observer.onUserActionRequired(intent);
17570            } catch (RemoteException re) {
17571            }
17572            return;
17573        }
17574        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17575        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17576        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17577            mContext.enforceCallingOrSelfPermission(
17578                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17579                    "deletePackage for user " + userId);
17580        }
17581
17582        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17583            try {
17584                observer.onPackageDeleted(packageName,
17585                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17586            } catch (RemoteException re) {
17587            }
17588            return;
17589        }
17590
17591        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17592            try {
17593                observer.onPackageDeleted(packageName,
17594                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17595            } catch (RemoteException re) {
17596            }
17597            return;
17598        }
17599
17600        if (DEBUG_REMOVE) {
17601            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17602                    + " deleteAllUsers: " + deleteAllUsers + " version="
17603                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17604                    ? "VERSION_CODE_HIGHEST" : versionCode));
17605        }
17606        // Queue up an async operation since the package deletion may take a little while.
17607        mHandler.post(new Runnable() {
17608            public void run() {
17609                mHandler.removeCallbacks(this);
17610                int returnCode;
17611                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17612                boolean doDeletePackage = true;
17613                if (ps != null) {
17614                    final boolean targetIsInstantApp =
17615                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17616                    doDeletePackage = !targetIsInstantApp
17617                            || canViewInstantApps;
17618                }
17619                if (doDeletePackage) {
17620                    if (!deleteAllUsers) {
17621                        returnCode = deletePackageX(internalPackageName, versionCode,
17622                                userId, deleteFlags);
17623                    } else {
17624                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17625                                internalPackageName, users);
17626                        // If nobody is blocking uninstall, proceed with delete for all users
17627                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17628                            returnCode = deletePackageX(internalPackageName, versionCode,
17629                                    userId, deleteFlags);
17630                        } else {
17631                            // Otherwise uninstall individually for users with blockUninstalls=false
17632                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17633                            for (int userId : users) {
17634                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17635                                    returnCode = deletePackageX(internalPackageName, versionCode,
17636                                            userId, userFlags);
17637                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17638                                        Slog.w(TAG, "Package delete failed for user " + userId
17639                                                + ", returnCode " + returnCode);
17640                                    }
17641                                }
17642                            }
17643                            // The app has only been marked uninstalled for certain users.
17644                            // We still need to report that delete was blocked
17645                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17646                        }
17647                    }
17648                } else {
17649                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17650                }
17651                try {
17652                    observer.onPackageDeleted(packageName, returnCode, null);
17653                } catch (RemoteException e) {
17654                    Log.i(TAG, "Observer no longer exists.");
17655                } //end catch
17656            } //end run
17657        });
17658    }
17659
17660    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17661        if (pkg.staticSharedLibName != null) {
17662            return pkg.manifestPackageName;
17663        }
17664        return pkg.packageName;
17665    }
17666
17667    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17668        // Handle renamed packages
17669        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17670        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17671
17672        // Is this a static library?
17673        LongSparseArray<SharedLibraryEntry> versionedLib =
17674                mStaticLibsByDeclaringPackage.get(packageName);
17675        if (versionedLib == null || versionedLib.size() <= 0) {
17676            return packageName;
17677        }
17678
17679        // Figure out which lib versions the caller can see
17680        LongSparseLongArray versionsCallerCanSee = null;
17681        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17682        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17683                && callingAppId != Process.ROOT_UID) {
17684            versionsCallerCanSee = new LongSparseLongArray();
17685            String libName = versionedLib.valueAt(0).info.getName();
17686            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17687            if (uidPackages != null) {
17688                for (String uidPackage : uidPackages) {
17689                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17690                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17691                    if (libIdx >= 0) {
17692                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17693                        versionsCallerCanSee.append(libVersion, libVersion);
17694                    }
17695                }
17696            }
17697        }
17698
17699        // Caller can see nothing - done
17700        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17701            return packageName;
17702        }
17703
17704        // Find the version the caller can see and the app version code
17705        SharedLibraryEntry highestVersion = null;
17706        final int versionCount = versionedLib.size();
17707        for (int i = 0; i < versionCount; i++) {
17708            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17709            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17710                    libEntry.info.getLongVersion()) < 0) {
17711                continue;
17712            }
17713            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17714            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17715                if (libVersionCode == versionCode) {
17716                    return libEntry.apk;
17717                }
17718            } else if (highestVersion == null) {
17719                highestVersion = libEntry;
17720            } else if (libVersionCode  > highestVersion.info
17721                    .getDeclaringPackage().getLongVersionCode()) {
17722                highestVersion = libEntry;
17723            }
17724        }
17725
17726        if (highestVersion != null) {
17727            return highestVersion.apk;
17728        }
17729
17730        return packageName;
17731    }
17732
17733    boolean isCallerVerifier(int callingUid) {
17734        final int callingUserId = UserHandle.getUserId(callingUid);
17735        return mRequiredVerifierPackage != null &&
17736                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17737    }
17738
17739    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17740        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17741              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17742            return true;
17743        }
17744        final int callingUserId = UserHandle.getUserId(callingUid);
17745        // If the caller installed the pkgName, then allow it to silently uninstall.
17746        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17747            return true;
17748        }
17749
17750        // Allow package verifier to silently uninstall.
17751        if (mRequiredVerifierPackage != null &&
17752                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17753            return true;
17754        }
17755
17756        // Allow package uninstaller to silently uninstall.
17757        if (mRequiredUninstallerPackage != null &&
17758                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17759            return true;
17760        }
17761
17762        // Allow storage manager to silently uninstall.
17763        if (mStorageManagerPackage != null &&
17764                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17765            return true;
17766        }
17767
17768        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17769        // uninstall for device owner provisioning.
17770        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17771                == PERMISSION_GRANTED) {
17772            return true;
17773        }
17774
17775        return false;
17776    }
17777
17778    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17779        int[] result = EMPTY_INT_ARRAY;
17780        for (int userId : userIds) {
17781            if (getBlockUninstallForUser(packageName, userId)) {
17782                result = ArrayUtils.appendInt(result, userId);
17783            }
17784        }
17785        return result;
17786    }
17787
17788    @Override
17789    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17790        final int callingUid = Binder.getCallingUid();
17791        if (getInstantAppPackageName(callingUid) != null
17792                && !isCallerSameApp(packageName, callingUid)) {
17793            return false;
17794        }
17795        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17796    }
17797
17798    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17799        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17800                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17801        try {
17802            if (dpm != null) {
17803                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17804                        /* callingUserOnly =*/ false);
17805                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17806                        : deviceOwnerComponentName.getPackageName();
17807                // Does the package contains the device owner?
17808                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17809                // this check is probably not needed, since DO should be registered as a device
17810                // admin on some user too. (Original bug for this: b/17657954)
17811                if (packageName.equals(deviceOwnerPackageName)) {
17812                    return true;
17813                }
17814                // Does it contain a device admin for any user?
17815                int[] users;
17816                if (userId == UserHandle.USER_ALL) {
17817                    users = sUserManager.getUserIds();
17818                } else {
17819                    users = new int[]{userId};
17820                }
17821                for (int i = 0; i < users.length; ++i) {
17822                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17823                        return true;
17824                    }
17825                }
17826            }
17827        } catch (RemoteException e) {
17828        }
17829        return false;
17830    }
17831
17832    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17833        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17834    }
17835
17836    /**
17837     *  This method is an internal method that could be get invoked either
17838     *  to delete an installed package or to clean up a failed installation.
17839     *  After deleting an installed package, a broadcast is sent to notify any
17840     *  listeners that the package has been removed. For cleaning up a failed
17841     *  installation, the broadcast is not necessary since the package's
17842     *  installation wouldn't have sent the initial broadcast either
17843     *  The key steps in deleting a package are
17844     *  deleting the package information in internal structures like mPackages,
17845     *  deleting the packages base directories through installd
17846     *  updating mSettings to reflect current status
17847     *  persisting settings for later use
17848     *  sending a broadcast if necessary
17849     */
17850    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17851        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17852        final boolean res;
17853
17854        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17855                ? UserHandle.USER_ALL : userId;
17856
17857        if (isPackageDeviceAdmin(packageName, removeUser)) {
17858            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17859            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17860        }
17861
17862        PackageSetting uninstalledPs = null;
17863        PackageParser.Package pkg = null;
17864
17865        // for the uninstall-updates case and restricted profiles, remember the per-
17866        // user handle installed state
17867        int[] allUsers;
17868        synchronized (mPackages) {
17869            uninstalledPs = mSettings.mPackages.get(packageName);
17870            if (uninstalledPs == null) {
17871                Slog.w(TAG, "Not removing non-existent package " + packageName);
17872                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17873            }
17874
17875            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17876                    && uninstalledPs.versionCode != versionCode) {
17877                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17878                        + uninstalledPs.versionCode + " != " + versionCode);
17879                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17880            }
17881
17882            // Static shared libs can be declared by any package, so let us not
17883            // allow removing a package if it provides a lib others depend on.
17884            pkg = mPackages.get(packageName);
17885
17886            allUsers = sUserManager.getUserIds();
17887
17888            if (pkg != null && pkg.staticSharedLibName != null) {
17889                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17890                        pkg.staticSharedLibVersion);
17891                if (libEntry != null) {
17892                    for (int currUserId : allUsers) {
17893                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17894                            continue;
17895                        }
17896                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17897                                libEntry.info, 0, currUserId);
17898                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17899                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17900                                    + " hosting lib " + libEntry.info.getName() + " version "
17901                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17902                                    + " for user " + currUserId);
17903                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17904                        }
17905                    }
17906                }
17907            }
17908
17909            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17910        }
17911
17912        final int freezeUser;
17913        if (isUpdatedSystemApp(uninstalledPs)
17914                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17915            // We're downgrading a system app, which will apply to all users, so
17916            // freeze them all during the downgrade
17917            freezeUser = UserHandle.USER_ALL;
17918        } else {
17919            freezeUser = removeUser;
17920        }
17921
17922        synchronized (mInstallLock) {
17923            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17924            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17925                    deleteFlags, "deletePackageX")) {
17926                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17927                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17928            }
17929            synchronized (mPackages) {
17930                if (res) {
17931                    if (pkg != null) {
17932                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17933                    }
17934                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17935                    updateInstantAppInstallerLocked(packageName);
17936                }
17937            }
17938        }
17939
17940        if (res) {
17941            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17942            info.sendPackageRemovedBroadcasts(killApp);
17943            info.sendSystemPackageUpdatedBroadcasts();
17944            info.sendSystemPackageAppearedBroadcasts();
17945        }
17946        // Force a gc here.
17947        Runtime.getRuntime().gc();
17948        // Delete the resources here after sending the broadcast to let
17949        // other processes clean up before deleting resources.
17950        if (info.args != null) {
17951            synchronized (mInstallLock) {
17952                info.args.doPostDeleteLI(true);
17953            }
17954        }
17955
17956        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17957    }
17958
17959    static class PackageRemovedInfo {
17960        final PackageSender packageSender;
17961        String removedPackage;
17962        String installerPackageName;
17963        int uid = -1;
17964        int removedAppId = -1;
17965        int[] origUsers;
17966        int[] removedUsers = null;
17967        int[] broadcastUsers = null;
17968        int[] instantUserIds = null;
17969        SparseArray<Integer> installReasons;
17970        boolean isRemovedPackageSystemUpdate = false;
17971        boolean isUpdate;
17972        boolean dataRemoved;
17973        boolean removedForAllUsers;
17974        boolean isStaticSharedLib;
17975        // Clean up resources deleted packages.
17976        InstallArgs args = null;
17977        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17978        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17979
17980        PackageRemovedInfo(PackageSender packageSender) {
17981            this.packageSender = packageSender;
17982        }
17983
17984        void sendPackageRemovedBroadcasts(boolean killApp) {
17985            sendPackageRemovedBroadcastInternal(killApp);
17986            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17987            for (int i = 0; i < childCount; i++) {
17988                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17989                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17990            }
17991        }
17992
17993        void sendSystemPackageUpdatedBroadcasts() {
17994            if (isRemovedPackageSystemUpdate) {
17995                sendSystemPackageUpdatedBroadcastsInternal();
17996                final int childCount = (removedChildPackages != null)
17997                        ? removedChildPackages.size() : 0;
17998                for (int i = 0; i < childCount; i++) {
17999                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18000                    if (childInfo.isRemovedPackageSystemUpdate) {
18001                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18002                    }
18003                }
18004            }
18005        }
18006
18007        void sendSystemPackageAppearedBroadcasts() {
18008            final int packageCount = (appearedChildPackages != null)
18009                    ? appearedChildPackages.size() : 0;
18010            for (int i = 0; i < packageCount; i++) {
18011                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18012                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18013                    true /*sendBootCompleted*/, false /*startReceiver*/,
18014                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18015            }
18016        }
18017
18018        private void sendSystemPackageUpdatedBroadcastsInternal() {
18019            Bundle extras = new Bundle(2);
18020            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18021            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18022            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18023                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18024            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18025                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18026            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18027                null, null, 0, removedPackage, null, null, null);
18028            if (installerPackageName != null) {
18029                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18030                        removedPackage, extras, 0 /*flags*/,
18031                        installerPackageName, null, null, null);
18032                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18033                        removedPackage, extras, 0 /*flags*/,
18034                        installerPackageName, null, null, null);
18035            }
18036        }
18037
18038        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18039            // Don't send static shared library removal broadcasts as these
18040            // libs are visible only the the apps that depend on them an one
18041            // cannot remove the library if it has a dependency.
18042            if (isStaticSharedLib) {
18043                return;
18044            }
18045            Bundle extras = new Bundle(2);
18046            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18047            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18048            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18049            if (isUpdate || isRemovedPackageSystemUpdate) {
18050                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18051            }
18052            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18053            if (removedPackage != null) {
18054                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18055                    removedPackage, extras, 0, null /*targetPackage*/, null,
18056                    broadcastUsers, instantUserIds);
18057                if (installerPackageName != null) {
18058                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18059                            removedPackage, extras, 0 /*flags*/,
18060                            installerPackageName, null, broadcastUsers, instantUserIds);
18061                }
18062                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18063                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18064                        removedPackage, extras,
18065                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18066                        null, null, broadcastUsers, instantUserIds);
18067                    packageSender.notifyPackageRemoved(removedPackage);
18068                }
18069            }
18070            if (removedAppId >= 0) {
18071                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18072                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18073                    null, null, broadcastUsers, instantUserIds);
18074            }
18075        }
18076
18077        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18078            removedUsers = userIds;
18079            if (removedUsers == null) {
18080                broadcastUsers = null;
18081                return;
18082            }
18083
18084            broadcastUsers = EMPTY_INT_ARRAY;
18085            instantUserIds = EMPTY_INT_ARRAY;
18086            for (int i = userIds.length - 1; i >= 0; --i) {
18087                final int userId = userIds[i];
18088                if (deletedPackageSetting.getInstantApp(userId)) {
18089                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18090                } else {
18091                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18092                }
18093            }
18094        }
18095    }
18096
18097    /*
18098     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18099     * flag is not set, the data directory is removed as well.
18100     * make sure this flag is set for partially installed apps. If not its meaningless to
18101     * delete a partially installed application.
18102     */
18103    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18104            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18105        String packageName = ps.name;
18106        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18107        // Retrieve object to delete permissions for shared user later on
18108        final PackageParser.Package deletedPkg;
18109        final PackageSetting deletedPs;
18110        // reader
18111        synchronized (mPackages) {
18112            deletedPkg = mPackages.get(packageName);
18113            deletedPs = mSettings.mPackages.get(packageName);
18114            if (outInfo != null) {
18115                outInfo.removedPackage = packageName;
18116                outInfo.installerPackageName = ps.installerPackageName;
18117                outInfo.isStaticSharedLib = deletedPkg != null
18118                        && deletedPkg.staticSharedLibName != null;
18119                outInfo.populateUsers(deletedPs == null ? null
18120                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18121            }
18122        }
18123
18124        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18125
18126        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18127            final PackageParser.Package resolvedPkg;
18128            if (deletedPkg != null) {
18129                resolvedPkg = deletedPkg;
18130            } else {
18131                // We don't have a parsed package when it lives on an ejected
18132                // adopted storage device, so fake something together
18133                resolvedPkg = new PackageParser.Package(ps.name);
18134                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18135            }
18136            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18137                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18138            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18139            if (outInfo != null) {
18140                outInfo.dataRemoved = true;
18141            }
18142            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18143        }
18144
18145        int removedAppId = -1;
18146
18147        // writer
18148        synchronized (mPackages) {
18149            boolean installedStateChanged = false;
18150            if (deletedPs != null) {
18151                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18152                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18153                    clearDefaultBrowserIfNeeded(packageName);
18154                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18155                    removedAppId = mSettings.removePackageLPw(packageName);
18156                    if (outInfo != null) {
18157                        outInfo.removedAppId = removedAppId;
18158                    }
18159                    mPermissionManager.updatePermissions(
18160                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18161                    if (deletedPs.sharedUser != null) {
18162                        // Remove permissions associated with package. Since runtime
18163                        // permissions are per user we have to kill the removed package
18164                        // or packages running under the shared user of the removed
18165                        // package if revoking the permissions requested only by the removed
18166                        // package is successful and this causes a change in gids.
18167                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18168                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18169                                    userId);
18170                            if (userIdToKill == UserHandle.USER_ALL
18171                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18172                                // If gids changed for this user, kill all affected packages.
18173                                mHandler.post(new Runnable() {
18174                                    @Override
18175                                    public void run() {
18176                                        // This has to happen with no lock held.
18177                                        killApplication(deletedPs.name, deletedPs.appId,
18178                                                KILL_APP_REASON_GIDS_CHANGED);
18179                                    }
18180                                });
18181                                break;
18182                            }
18183                        }
18184                    }
18185                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18186                }
18187                // make sure to preserve per-user disabled state if this removal was just
18188                // a downgrade of a system app to the factory package
18189                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18190                    if (DEBUG_REMOVE) {
18191                        Slog.d(TAG, "Propagating install state across downgrade");
18192                    }
18193                    for (int userId : allUserHandles) {
18194                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18195                        if (DEBUG_REMOVE) {
18196                            Slog.d(TAG, "    user " + userId + " => " + installed);
18197                        }
18198                        if (installed != ps.getInstalled(userId)) {
18199                            installedStateChanged = true;
18200                        }
18201                        ps.setInstalled(installed, userId);
18202                    }
18203                }
18204            }
18205            // can downgrade to reader
18206            if (writeSettings) {
18207                // Save settings now
18208                mSettings.writeLPr();
18209            }
18210            if (installedStateChanged) {
18211                mSettings.writeKernelMappingLPr(ps);
18212            }
18213        }
18214        if (removedAppId != -1) {
18215            // A user ID was deleted here. Go through all users and remove it
18216            // from KeyStore.
18217            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18218        }
18219    }
18220
18221    static boolean locationIsPrivileged(String path) {
18222        try {
18223            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18224            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18225            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18226            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18227            return path.startsWith(privilegedAppDir.getCanonicalPath())
18228                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18229                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18230                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18231        } catch (IOException e) {
18232            Slog.e(TAG, "Unable to access code path " + path);
18233        }
18234        return false;
18235    }
18236
18237    static boolean locationIsOem(String path) {
18238        try {
18239            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18240        } catch (IOException e) {
18241            Slog.e(TAG, "Unable to access code path " + path);
18242        }
18243        return false;
18244    }
18245
18246    static boolean locationIsVendor(String path) {
18247        try {
18248            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18249                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18250        } catch (IOException e) {
18251            Slog.e(TAG, "Unable to access code path " + path);
18252        }
18253        return false;
18254    }
18255
18256    static boolean locationIsProduct(String path) {
18257        try {
18258            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18259        } catch (IOException e) {
18260            Slog.e(TAG, "Unable to access code path " + path);
18261        }
18262        return false;
18263    }
18264
18265    /*
18266     * Tries to delete system package.
18267     */
18268    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18269            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18270            boolean writeSettings) {
18271        if (deletedPs.parentPackageName != null) {
18272            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18273            return false;
18274        }
18275
18276        final boolean applyUserRestrictions
18277                = (allUserHandles != null) && (outInfo.origUsers != null);
18278        final PackageSetting disabledPs;
18279        // Confirm if the system package has been updated
18280        // An updated system app can be deleted. This will also have to restore
18281        // the system pkg from system partition
18282        // reader
18283        synchronized (mPackages) {
18284            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18285        }
18286
18287        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18288                + " disabledPs=" + disabledPs);
18289
18290        if (disabledPs == null) {
18291            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18292            return false;
18293        } else if (DEBUG_REMOVE) {
18294            Slog.d(TAG, "Deleting system pkg from data partition");
18295        }
18296
18297        if (DEBUG_REMOVE) {
18298            if (applyUserRestrictions) {
18299                Slog.d(TAG, "Remembering install states:");
18300                for (int userId : allUserHandles) {
18301                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18302                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18303                }
18304            }
18305        }
18306
18307        // Delete the updated package
18308        outInfo.isRemovedPackageSystemUpdate = true;
18309        if (outInfo.removedChildPackages != null) {
18310            final int childCount = (deletedPs.childPackageNames != null)
18311                    ? deletedPs.childPackageNames.size() : 0;
18312            for (int i = 0; i < childCount; i++) {
18313                String childPackageName = deletedPs.childPackageNames.get(i);
18314                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18315                        .contains(childPackageName)) {
18316                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18317                            childPackageName);
18318                    if (childInfo != null) {
18319                        childInfo.isRemovedPackageSystemUpdate = true;
18320                    }
18321                }
18322            }
18323        }
18324
18325        if (disabledPs.versionCode < deletedPs.versionCode) {
18326            // Delete data for downgrades
18327            flags &= ~PackageManager.DELETE_KEEP_DATA;
18328        } else {
18329            // Preserve data by setting flag
18330            flags |= PackageManager.DELETE_KEEP_DATA;
18331        }
18332
18333        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18334                outInfo, writeSettings, disabledPs.pkg);
18335        if (!ret) {
18336            return false;
18337        }
18338
18339        // writer
18340        synchronized (mPackages) {
18341            // NOTE: The system package always needs to be enabled; even if it's for
18342            // a compressed stub. If we don't, installing the system package fails
18343            // during scan [scanning checks the disabled packages]. We will reverse
18344            // this later, after we've "installed" the stub.
18345            // Reinstate the old system package
18346            enableSystemPackageLPw(disabledPs.pkg);
18347            // Remove any native libraries from the upgraded package.
18348            removeNativeBinariesLI(deletedPs);
18349        }
18350
18351        // Install the system package
18352        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18353        try {
18354            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18355                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18356        } catch (PackageManagerException e) {
18357            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18358                    + e.getMessage());
18359            return false;
18360        } finally {
18361            if (disabledPs.pkg.isStub) {
18362                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18363            }
18364        }
18365        return true;
18366    }
18367
18368    /**
18369     * Installs a package that's already on the system partition.
18370     */
18371    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18372            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18373            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18374                    throws PackageManagerException {
18375        @ParseFlags int parseFlags =
18376                mDefParseFlags
18377                | PackageParser.PARSE_MUST_BE_APK
18378                | PackageParser.PARSE_IS_SYSTEM_DIR;
18379        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18380        if (isPrivileged || locationIsPrivileged(codePathString)) {
18381            scanFlags |= SCAN_AS_PRIVILEGED;
18382        }
18383        if (locationIsOem(codePathString)) {
18384            scanFlags |= SCAN_AS_OEM;
18385        }
18386        if (locationIsVendor(codePathString)) {
18387            scanFlags |= SCAN_AS_VENDOR;
18388        }
18389        if (locationIsProduct(codePathString)) {
18390            scanFlags |= SCAN_AS_PRODUCT;
18391        }
18392
18393        final File codePath = new File(codePathString);
18394        final PackageParser.Package pkg =
18395                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18396
18397        try {
18398            // update shared libraries for the newly re-installed system package
18399            updateSharedLibrariesLPr(pkg, null);
18400        } catch (PackageManagerException e) {
18401            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18402        }
18403
18404        prepareAppDataAfterInstallLIF(pkg);
18405
18406        // writer
18407        synchronized (mPackages) {
18408            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18409
18410            // Propagate the permissions state as we do not want to drop on the floor
18411            // runtime permissions. The update permissions method below will take
18412            // care of removing obsolete permissions and grant install permissions.
18413            if (origPermissionState != null) {
18414                ps.getPermissionsState().copyFrom(origPermissionState);
18415            }
18416            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18417                    mPermissionCallback);
18418
18419            final boolean applyUserRestrictions
18420                    = (allUserHandles != null) && (origUserHandles != null);
18421            if (applyUserRestrictions) {
18422                boolean installedStateChanged = false;
18423                if (DEBUG_REMOVE) {
18424                    Slog.d(TAG, "Propagating install state across reinstall");
18425                }
18426                for (int userId : allUserHandles) {
18427                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18428                    if (DEBUG_REMOVE) {
18429                        Slog.d(TAG, "    user " + userId + " => " + installed);
18430                    }
18431                    if (installed != ps.getInstalled(userId)) {
18432                        installedStateChanged = true;
18433                    }
18434                    ps.setInstalled(installed, userId);
18435
18436                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18437                }
18438                // Regardless of writeSettings we need to ensure that this restriction
18439                // state propagation is persisted
18440                mSettings.writeAllUsersPackageRestrictionsLPr();
18441                if (installedStateChanged) {
18442                    mSettings.writeKernelMappingLPr(ps);
18443                }
18444            }
18445            // can downgrade to reader here
18446            if (writeSettings) {
18447                mSettings.writeLPr();
18448            }
18449        }
18450        return pkg;
18451    }
18452
18453    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18454            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18455            PackageRemovedInfo outInfo, boolean writeSettings,
18456            PackageParser.Package replacingPackage) {
18457        synchronized (mPackages) {
18458            if (outInfo != null) {
18459                outInfo.uid = ps.appId;
18460            }
18461
18462            if (outInfo != null && outInfo.removedChildPackages != null) {
18463                final int childCount = (ps.childPackageNames != null)
18464                        ? ps.childPackageNames.size() : 0;
18465                for (int i = 0; i < childCount; i++) {
18466                    String childPackageName = ps.childPackageNames.get(i);
18467                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18468                    if (childPs == null) {
18469                        return false;
18470                    }
18471                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18472                            childPackageName);
18473                    if (childInfo != null) {
18474                        childInfo.uid = childPs.appId;
18475                    }
18476                }
18477            }
18478        }
18479
18480        // Delete package data from internal structures and also remove data if flag is set
18481        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18482
18483        // Delete the child packages data
18484        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18485        for (int i = 0; i < childCount; i++) {
18486            PackageSetting childPs;
18487            synchronized (mPackages) {
18488                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18489            }
18490            if (childPs != null) {
18491                PackageRemovedInfo childOutInfo = (outInfo != null
18492                        && outInfo.removedChildPackages != null)
18493                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18494                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18495                        && (replacingPackage != null
18496                        && !replacingPackage.hasChildPackage(childPs.name))
18497                        ? flags & ~DELETE_KEEP_DATA : flags;
18498                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18499                        deleteFlags, writeSettings);
18500            }
18501        }
18502
18503        // Delete application code and resources only for parent packages
18504        if (ps.parentPackageName == null) {
18505            if (deleteCodeAndResources && (outInfo != null)) {
18506                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18507                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18508                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18509            }
18510        }
18511
18512        return true;
18513    }
18514
18515    @Override
18516    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18517            int userId) {
18518        mContext.enforceCallingOrSelfPermission(
18519                android.Manifest.permission.DELETE_PACKAGES, null);
18520        synchronized (mPackages) {
18521            // Cannot block uninstall of static shared libs as they are
18522            // considered a part of the using app (emulating static linking).
18523            // Also static libs are installed always on internal storage.
18524            PackageParser.Package pkg = mPackages.get(packageName);
18525            if (pkg != null && pkg.staticSharedLibName != null) {
18526                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18527                        + " providing static shared library: " + pkg.staticSharedLibName);
18528                return false;
18529            }
18530            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18531            mSettings.writePackageRestrictionsLPr(userId);
18532        }
18533        return true;
18534    }
18535
18536    @Override
18537    public boolean getBlockUninstallForUser(String packageName, int userId) {
18538        synchronized (mPackages) {
18539            final PackageSetting ps = mSettings.mPackages.get(packageName);
18540            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18541                return false;
18542            }
18543            return mSettings.getBlockUninstallLPr(userId, packageName);
18544        }
18545    }
18546
18547    @Override
18548    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18549        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18550        synchronized (mPackages) {
18551            PackageSetting ps = mSettings.mPackages.get(packageName);
18552            if (ps == null) {
18553                Log.w(TAG, "Package doesn't exist: " + packageName);
18554                return false;
18555            }
18556            if (systemUserApp) {
18557                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18558            } else {
18559                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18560            }
18561            mSettings.writeLPr();
18562        }
18563        return true;
18564    }
18565
18566    /*
18567     * This method handles package deletion in general
18568     */
18569    private boolean deletePackageLIF(String packageName, UserHandle user,
18570            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18571            PackageRemovedInfo outInfo, boolean writeSettings,
18572            PackageParser.Package replacingPackage) {
18573        if (packageName == null) {
18574            Slog.w(TAG, "Attempt to delete null packageName.");
18575            return false;
18576        }
18577
18578        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18579
18580        PackageSetting ps;
18581        synchronized (mPackages) {
18582            ps = mSettings.mPackages.get(packageName);
18583            if (ps == null) {
18584                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18585                return false;
18586            }
18587
18588            if (ps.parentPackageName != null && (!isSystemApp(ps)
18589                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18590                if (DEBUG_REMOVE) {
18591                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18592                            + ((user == null) ? UserHandle.USER_ALL : user));
18593                }
18594                final int removedUserId = (user != null) ? user.getIdentifier()
18595                        : UserHandle.USER_ALL;
18596                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18597                    return false;
18598                }
18599                markPackageUninstalledForUserLPw(ps, user);
18600                scheduleWritePackageRestrictionsLocked(user);
18601                return true;
18602            }
18603        }
18604
18605        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18606                && user.getIdentifier() != UserHandle.USER_ALL)) {
18607            // The caller is asking that the package only be deleted for a single
18608            // user.  To do this, we just mark its uninstalled state and delete
18609            // its data. If this is a system app, we only allow this to happen if
18610            // they have set the special DELETE_SYSTEM_APP which requests different
18611            // semantics than normal for uninstalling system apps.
18612            markPackageUninstalledForUserLPw(ps, user);
18613
18614            if (!isSystemApp(ps)) {
18615                // Do not uninstall the APK if an app should be cached
18616                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18617                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18618                    // Other user still have this package installed, so all
18619                    // we need to do is clear this user's data and save that
18620                    // it is uninstalled.
18621                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18622                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18623                        return false;
18624                    }
18625                    scheduleWritePackageRestrictionsLocked(user);
18626                    return true;
18627                } else {
18628                    // We need to set it back to 'installed' so the uninstall
18629                    // broadcasts will be sent correctly.
18630                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18631                    ps.setInstalled(true, user.getIdentifier());
18632                    mSettings.writeKernelMappingLPr(ps);
18633                }
18634            } else {
18635                // This is a system app, so we assume that the
18636                // other users still have this package installed, so all
18637                // we need to do is clear this user's data and save that
18638                // it is uninstalled.
18639                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18640                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18641                    return false;
18642                }
18643                scheduleWritePackageRestrictionsLocked(user);
18644                return true;
18645            }
18646        }
18647
18648        // If we are deleting a composite package for all users, keep track
18649        // of result for each child.
18650        if (ps.childPackageNames != null && outInfo != null) {
18651            synchronized (mPackages) {
18652                final int childCount = ps.childPackageNames.size();
18653                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18654                for (int i = 0; i < childCount; i++) {
18655                    String childPackageName = ps.childPackageNames.get(i);
18656                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18657                    childInfo.removedPackage = childPackageName;
18658                    childInfo.installerPackageName = ps.installerPackageName;
18659                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18660                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18661                    if (childPs != null) {
18662                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18663                    }
18664                }
18665            }
18666        }
18667
18668        boolean ret = false;
18669        if (isSystemApp(ps)) {
18670            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18671            // When an updated system application is deleted we delete the existing resources
18672            // as well and fall back to existing code in system partition
18673            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18674        } else {
18675            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18676            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18677                    outInfo, writeSettings, replacingPackage);
18678        }
18679
18680        // Take a note whether we deleted the package for all users
18681        if (outInfo != null) {
18682            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18683            if (outInfo.removedChildPackages != null) {
18684                synchronized (mPackages) {
18685                    final int childCount = outInfo.removedChildPackages.size();
18686                    for (int i = 0; i < childCount; i++) {
18687                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18688                        if (childInfo != null) {
18689                            childInfo.removedForAllUsers = mPackages.get(
18690                                    childInfo.removedPackage) == null;
18691                        }
18692                    }
18693                }
18694            }
18695            // If we uninstalled an update to a system app there may be some
18696            // child packages that appeared as they are declared in the system
18697            // app but were not declared in the update.
18698            if (isSystemApp(ps)) {
18699                synchronized (mPackages) {
18700                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18701                    final int childCount = (updatedPs.childPackageNames != null)
18702                            ? updatedPs.childPackageNames.size() : 0;
18703                    for (int i = 0; i < childCount; i++) {
18704                        String childPackageName = updatedPs.childPackageNames.get(i);
18705                        if (outInfo.removedChildPackages == null
18706                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18707                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18708                            if (childPs == null) {
18709                                continue;
18710                            }
18711                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18712                            installRes.name = childPackageName;
18713                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18714                            installRes.pkg = mPackages.get(childPackageName);
18715                            installRes.uid = childPs.pkg.applicationInfo.uid;
18716                            if (outInfo.appearedChildPackages == null) {
18717                                outInfo.appearedChildPackages = new ArrayMap<>();
18718                            }
18719                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18720                        }
18721                    }
18722                }
18723            }
18724        }
18725
18726        return ret;
18727    }
18728
18729    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18730        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18731                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18732        for (int nextUserId : userIds) {
18733            if (DEBUG_REMOVE) {
18734                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18735            }
18736            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18737                    false /*installed*/,
18738                    true /*stopped*/,
18739                    true /*notLaunched*/,
18740                    false /*hidden*/,
18741                    false /*suspended*/,
18742                    false /*instantApp*/,
18743                    false /*virtualPreload*/,
18744                    null /*lastDisableAppCaller*/,
18745                    null /*enabledComponents*/,
18746                    null /*disabledComponents*/,
18747                    ps.readUserState(nextUserId).domainVerificationStatus,
18748                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18749                    null /*harmfulAppWarning*/);
18750        }
18751        mSettings.writeKernelMappingLPr(ps);
18752    }
18753
18754    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18755            PackageRemovedInfo outInfo) {
18756        final PackageParser.Package pkg;
18757        synchronized (mPackages) {
18758            pkg = mPackages.get(ps.name);
18759        }
18760
18761        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18762                : new int[] {userId};
18763        for (int nextUserId : userIds) {
18764            if (DEBUG_REMOVE) {
18765                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18766                        + nextUserId);
18767            }
18768
18769            destroyAppDataLIF(pkg, userId,
18770                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18771            destroyAppProfilesLIF(pkg, userId);
18772            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18773            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18774            schedulePackageCleaning(ps.name, nextUserId, false);
18775            synchronized (mPackages) {
18776                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18777                    scheduleWritePackageRestrictionsLocked(nextUserId);
18778                }
18779                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18780            }
18781        }
18782
18783        if (outInfo != null) {
18784            outInfo.removedPackage = ps.name;
18785            outInfo.installerPackageName = ps.installerPackageName;
18786            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18787            outInfo.removedAppId = ps.appId;
18788            outInfo.removedUsers = userIds;
18789            outInfo.broadcastUsers = userIds;
18790        }
18791
18792        return true;
18793    }
18794
18795    private static final class ClearStorageConnection implements ServiceConnection {
18796        IMediaContainerService mContainerService;
18797
18798        @Override
18799        public void onServiceConnected(ComponentName name, IBinder service) {
18800            synchronized (this) {
18801                mContainerService = IMediaContainerService.Stub
18802                        .asInterface(Binder.allowBlocking(service));
18803                notifyAll();
18804            }
18805        }
18806
18807        @Override
18808        public void onServiceDisconnected(ComponentName name) {
18809        }
18810    }
18811
18812    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18813        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18814
18815        final boolean mounted;
18816        if (Environment.isExternalStorageEmulated()) {
18817            mounted = true;
18818        } else {
18819            final String status = Environment.getExternalStorageState();
18820
18821            mounted = status.equals(Environment.MEDIA_MOUNTED)
18822                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18823        }
18824
18825        if (!mounted) {
18826            return;
18827        }
18828
18829        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18830        int[] users;
18831        if (userId == UserHandle.USER_ALL) {
18832            users = sUserManager.getUserIds();
18833        } else {
18834            users = new int[] { userId };
18835        }
18836        final ClearStorageConnection conn = new ClearStorageConnection();
18837        if (mContext.bindServiceAsUser(
18838                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18839            try {
18840                for (int curUser : users) {
18841                    long timeout = SystemClock.uptimeMillis() + 5000;
18842                    synchronized (conn) {
18843                        long now;
18844                        while (conn.mContainerService == null &&
18845                                (now = SystemClock.uptimeMillis()) < timeout) {
18846                            try {
18847                                conn.wait(timeout - now);
18848                            } catch (InterruptedException e) {
18849                            }
18850                        }
18851                    }
18852                    if (conn.mContainerService == null) {
18853                        return;
18854                    }
18855
18856                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18857                    clearDirectory(conn.mContainerService,
18858                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18859                    if (allData) {
18860                        clearDirectory(conn.mContainerService,
18861                                userEnv.buildExternalStorageAppDataDirs(packageName));
18862                        clearDirectory(conn.mContainerService,
18863                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18864                    }
18865                }
18866            } finally {
18867                mContext.unbindService(conn);
18868            }
18869        }
18870    }
18871
18872    @Override
18873    public void clearApplicationProfileData(String packageName) {
18874        enforceSystemOrRoot("Only the system can clear all profile data");
18875
18876        final PackageParser.Package pkg;
18877        synchronized (mPackages) {
18878            pkg = mPackages.get(packageName);
18879        }
18880
18881        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18882            synchronized (mInstallLock) {
18883                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18884            }
18885        }
18886    }
18887
18888    @Override
18889    public void clearApplicationUserData(final String packageName,
18890            final IPackageDataObserver observer, final int userId) {
18891        mContext.enforceCallingOrSelfPermission(
18892                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18893
18894        final int callingUid = Binder.getCallingUid();
18895        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18896                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18897
18898        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18899        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18900        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18901            throw new SecurityException("Cannot clear data for a protected package: "
18902                    + packageName);
18903        }
18904        // Queue up an async operation since the package deletion may take a little while.
18905        mHandler.post(new Runnable() {
18906            public void run() {
18907                mHandler.removeCallbacks(this);
18908                final boolean succeeded;
18909                if (!filterApp) {
18910                    try (PackageFreezer freezer = freezePackage(packageName,
18911                            "clearApplicationUserData")) {
18912                        synchronized (mInstallLock) {
18913                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18914                        }
18915                        clearExternalStorageDataSync(packageName, userId, true);
18916                        synchronized (mPackages) {
18917                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18918                                    packageName, userId);
18919                        }
18920                    }
18921                    if (succeeded) {
18922                        // invoke DeviceStorageMonitor's update method to clear any notifications
18923                        DeviceStorageMonitorInternal dsm = LocalServices
18924                                .getService(DeviceStorageMonitorInternal.class);
18925                        if (dsm != null) {
18926                            dsm.checkMemory();
18927                        }
18928                    }
18929                } else {
18930                    succeeded = false;
18931                }
18932                if (observer != null) {
18933                    try {
18934                        observer.onRemoveCompleted(packageName, succeeded);
18935                    } catch (RemoteException e) {
18936                        Log.i(TAG, "Observer no longer exists.");
18937                    }
18938                } //end if observer
18939            } //end run
18940        });
18941    }
18942
18943    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18944        if (packageName == null) {
18945            Slog.w(TAG, "Attempt to delete null packageName.");
18946            return false;
18947        }
18948
18949        // Try finding details about the requested package
18950        PackageParser.Package pkg;
18951        synchronized (mPackages) {
18952            pkg = mPackages.get(packageName);
18953            if (pkg == null) {
18954                final PackageSetting ps = mSettings.mPackages.get(packageName);
18955                if (ps != null) {
18956                    pkg = ps.pkg;
18957                }
18958            }
18959
18960            if (pkg == null) {
18961                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18962                return false;
18963            }
18964
18965            PackageSetting ps = (PackageSetting) pkg.mExtras;
18966            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18967        }
18968
18969        clearAppDataLIF(pkg, userId,
18970                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18971
18972        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18973        removeKeystoreDataIfNeeded(userId, appId);
18974
18975        UserManagerInternal umInternal = getUserManagerInternal();
18976        final int flags;
18977        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18978            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18979        } else if (umInternal.isUserRunning(userId)) {
18980            flags = StorageManager.FLAG_STORAGE_DE;
18981        } else {
18982            flags = 0;
18983        }
18984        prepareAppDataContentsLIF(pkg, userId, flags);
18985
18986        return true;
18987    }
18988
18989    /**
18990     * Reverts user permission state changes (permissions and flags) in
18991     * all packages for a given user.
18992     *
18993     * @param userId The device user for which to do a reset.
18994     */
18995    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18996        final int packageCount = mPackages.size();
18997        for (int i = 0; i < packageCount; i++) {
18998            PackageParser.Package pkg = mPackages.valueAt(i);
18999            PackageSetting ps = (PackageSetting) pkg.mExtras;
19000            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19001        }
19002    }
19003
19004    private void resetNetworkPolicies(int userId) {
19005        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19006    }
19007
19008    /**
19009     * Reverts user permission state changes (permissions and flags).
19010     *
19011     * @param ps The package for which to reset.
19012     * @param userId The device user for which to do a reset.
19013     */
19014    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19015            final PackageSetting ps, final int userId) {
19016        if (ps.pkg == null) {
19017            return;
19018        }
19019
19020        // These are flags that can change base on user actions.
19021        final int userSettableMask = FLAG_PERMISSION_USER_SET
19022                | FLAG_PERMISSION_USER_FIXED
19023                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19024                | FLAG_PERMISSION_REVIEW_REQUIRED;
19025
19026        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19027                | FLAG_PERMISSION_POLICY_FIXED;
19028
19029        boolean writeInstallPermissions = false;
19030        boolean writeRuntimePermissions = false;
19031
19032        final int permissionCount = ps.pkg.requestedPermissions.size();
19033        for (int i = 0; i < permissionCount; i++) {
19034            final String permName = ps.pkg.requestedPermissions.get(i);
19035            final BasePermission bp =
19036                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19037            if (bp == null) {
19038                continue;
19039            }
19040
19041            // If shared user we just reset the state to which only this app contributed.
19042            if (ps.sharedUser != null) {
19043                boolean used = false;
19044                final int packageCount = ps.sharedUser.packages.size();
19045                for (int j = 0; j < packageCount; j++) {
19046                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19047                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19048                            && pkg.pkg.requestedPermissions.contains(permName)) {
19049                        used = true;
19050                        break;
19051                    }
19052                }
19053                if (used) {
19054                    continue;
19055                }
19056            }
19057
19058            final PermissionsState permissionsState = ps.getPermissionsState();
19059
19060            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19061
19062            // Always clear the user settable flags.
19063            final boolean hasInstallState =
19064                    permissionsState.getInstallPermissionState(permName) != null;
19065            // If permission review is enabled and this is a legacy app, mark the
19066            // permission as requiring a review as this is the initial state.
19067            int flags = 0;
19068            if (mSettings.mPermissions.mPermissionReviewRequired
19069                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19070                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19071            }
19072            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19073                if (hasInstallState) {
19074                    writeInstallPermissions = true;
19075                } else {
19076                    writeRuntimePermissions = true;
19077                }
19078            }
19079
19080            // Below is only runtime permission handling.
19081            if (!bp.isRuntime()) {
19082                continue;
19083            }
19084
19085            // Never clobber system or policy.
19086            if ((oldFlags & policyOrSystemFlags) != 0) {
19087                continue;
19088            }
19089
19090            // If this permission was granted by default, make sure it is.
19091            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19092                if (permissionsState.grantRuntimePermission(bp, userId)
19093                        != PERMISSION_OPERATION_FAILURE) {
19094                    writeRuntimePermissions = true;
19095                }
19096            // If permission review is enabled the permissions for a legacy apps
19097            // are represented as constantly granted runtime ones, so don't revoke.
19098            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19099                // Otherwise, reset the permission.
19100                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19101                switch (revokeResult) {
19102                    case PERMISSION_OPERATION_SUCCESS:
19103                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19104                        writeRuntimePermissions = true;
19105                        final int appId = ps.appId;
19106                        mHandler.post(new Runnable() {
19107                            @Override
19108                            public void run() {
19109                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19110                            }
19111                        });
19112                    } break;
19113                }
19114            }
19115        }
19116
19117        // Synchronously write as we are taking permissions away.
19118        if (writeRuntimePermissions) {
19119            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19120        }
19121
19122        // Synchronously write as we are taking permissions away.
19123        if (writeInstallPermissions) {
19124            mSettings.writeLPr();
19125        }
19126    }
19127
19128    /**
19129     * Remove entries from the keystore daemon. Will only remove it if the
19130     * {@code appId} is valid.
19131     */
19132    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19133        if (appId < 0) {
19134            return;
19135        }
19136
19137        final KeyStore keyStore = KeyStore.getInstance();
19138        if (keyStore != null) {
19139            if (userId == UserHandle.USER_ALL) {
19140                for (final int individual : sUserManager.getUserIds()) {
19141                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19142                }
19143            } else {
19144                keyStore.clearUid(UserHandle.getUid(userId, appId));
19145            }
19146        } else {
19147            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19148        }
19149    }
19150
19151    @Override
19152    public void deleteApplicationCacheFiles(final String packageName,
19153            final IPackageDataObserver observer) {
19154        final int userId = UserHandle.getCallingUserId();
19155        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19156    }
19157
19158    @Override
19159    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19160            final IPackageDataObserver observer) {
19161        final int callingUid = Binder.getCallingUid();
19162        if (mContext.checkCallingOrSelfPermission(
19163                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19164                != PackageManager.PERMISSION_GRANTED) {
19165            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19166            if (mContext.checkCallingOrSelfPermission(
19167                    android.Manifest.permission.DELETE_CACHE_FILES)
19168                    == PackageManager.PERMISSION_GRANTED) {
19169                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19170                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19171                        ", silently ignoring");
19172                return;
19173            }
19174            mContext.enforceCallingOrSelfPermission(
19175                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19176        }
19177        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19178                /* requireFullPermission= */ true, /* checkShell= */ false,
19179                "delete application cache files");
19180        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19181                android.Manifest.permission.ACCESS_INSTANT_APPS);
19182
19183        final PackageParser.Package pkg;
19184        synchronized (mPackages) {
19185            pkg = mPackages.get(packageName);
19186        }
19187
19188        // Queue up an async operation since the package deletion may take a little while.
19189        mHandler.post(new Runnable() {
19190            public void run() {
19191                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19192                boolean doClearData = true;
19193                if (ps != null) {
19194                    final boolean targetIsInstantApp =
19195                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19196                    doClearData = !targetIsInstantApp
19197                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19198                }
19199                if (doClearData) {
19200                    synchronized (mInstallLock) {
19201                        final int flags = StorageManager.FLAG_STORAGE_DE
19202                                | StorageManager.FLAG_STORAGE_CE;
19203                        // We're only clearing cache files, so we don't care if the
19204                        // app is unfrozen and still able to run
19205                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19206                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19207                    }
19208                    clearExternalStorageDataSync(packageName, userId, false);
19209                }
19210                if (observer != null) {
19211                    try {
19212                        observer.onRemoveCompleted(packageName, true);
19213                    } catch (RemoteException e) {
19214                        Log.i(TAG, "Observer no longer exists.");
19215                    }
19216                }
19217            }
19218        });
19219    }
19220
19221    @Override
19222    public void getPackageSizeInfo(final String packageName, int userHandle,
19223            final IPackageStatsObserver observer) {
19224        throw new UnsupportedOperationException(
19225                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19226    }
19227
19228    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19229        final PackageSetting ps;
19230        synchronized (mPackages) {
19231            ps = mSettings.mPackages.get(packageName);
19232            if (ps == null) {
19233                Slog.w(TAG, "Failed to find settings for " + packageName);
19234                return false;
19235            }
19236        }
19237
19238        final String[] packageNames = { packageName };
19239        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19240        final String[] codePaths = { ps.codePathString };
19241
19242        try {
19243            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19244                    ps.appId, ceDataInodes, codePaths, stats);
19245
19246            // For now, ignore code size of packages on system partition
19247            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19248                stats.codeSize = 0;
19249            }
19250
19251            // External clients expect these to be tracked separately
19252            stats.dataSize -= stats.cacheSize;
19253
19254        } catch (InstallerException e) {
19255            Slog.w(TAG, String.valueOf(e));
19256            return false;
19257        }
19258
19259        return true;
19260    }
19261
19262    private int getUidTargetSdkVersionLockedLPr(int uid) {
19263        Object obj = mSettings.getUserIdLPr(uid);
19264        if (obj instanceof SharedUserSetting) {
19265            final SharedUserSetting sus = (SharedUserSetting) obj;
19266            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19267            final Iterator<PackageSetting> it = sus.packages.iterator();
19268            while (it.hasNext()) {
19269                final PackageSetting ps = it.next();
19270                if (ps.pkg != null) {
19271                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19272                    if (v < vers) vers = v;
19273                }
19274            }
19275            return vers;
19276        } else if (obj instanceof PackageSetting) {
19277            final PackageSetting ps = (PackageSetting) obj;
19278            if (ps.pkg != null) {
19279                return ps.pkg.applicationInfo.targetSdkVersion;
19280            }
19281        }
19282        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19283    }
19284
19285    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19286        final PackageParser.Package p = mPackages.get(packageName);
19287        if (p != null) {
19288            return p.applicationInfo.targetSdkVersion;
19289        }
19290        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19291    }
19292
19293    @Override
19294    public void addPreferredActivity(IntentFilter filter, int match,
19295            ComponentName[] set, ComponentName activity, int userId) {
19296        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19297                "Adding preferred");
19298    }
19299
19300    private void addPreferredActivityInternal(IntentFilter filter, int match,
19301            ComponentName[] set, ComponentName activity, boolean always, int userId,
19302            String opname) {
19303        // writer
19304        int callingUid = Binder.getCallingUid();
19305        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19306                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19307        if (filter.countActions() == 0) {
19308            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19309            return;
19310        }
19311        synchronized (mPackages) {
19312            if (mContext.checkCallingOrSelfPermission(
19313                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19314                    != PackageManager.PERMISSION_GRANTED) {
19315                if (getUidTargetSdkVersionLockedLPr(callingUid)
19316                        < Build.VERSION_CODES.FROYO) {
19317                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19318                            + callingUid);
19319                    return;
19320                }
19321                mContext.enforceCallingOrSelfPermission(
19322                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19323            }
19324
19325            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19326            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19327                    + userId + ":");
19328            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19329            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19330            scheduleWritePackageRestrictionsLocked(userId);
19331            postPreferredActivityChangedBroadcast(userId);
19332        }
19333    }
19334
19335    private void postPreferredActivityChangedBroadcast(int userId) {
19336        mHandler.post(() -> {
19337            final IActivityManager am = ActivityManager.getService();
19338            if (am == null) {
19339                return;
19340            }
19341
19342            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19343            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19344            try {
19345                am.broadcastIntent(null, intent, null, null,
19346                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19347                        null, false, false, userId);
19348            } catch (RemoteException e) {
19349            }
19350        });
19351    }
19352
19353    @Override
19354    public void replacePreferredActivity(IntentFilter filter, int match,
19355            ComponentName[] set, ComponentName activity, int userId) {
19356        if (filter.countActions() != 1) {
19357            throw new IllegalArgumentException(
19358                    "replacePreferredActivity expects filter to have only 1 action.");
19359        }
19360        if (filter.countDataAuthorities() != 0
19361                || filter.countDataPaths() != 0
19362                || filter.countDataSchemes() > 1
19363                || filter.countDataTypes() != 0) {
19364            throw new IllegalArgumentException(
19365                    "replacePreferredActivity expects filter to have no data authorities, " +
19366                    "paths, or types; and at most one scheme.");
19367        }
19368
19369        final int callingUid = Binder.getCallingUid();
19370        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19371                true /* requireFullPermission */, false /* checkShell */,
19372                "replace preferred activity");
19373        synchronized (mPackages) {
19374            if (mContext.checkCallingOrSelfPermission(
19375                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19376                    != PackageManager.PERMISSION_GRANTED) {
19377                if (getUidTargetSdkVersionLockedLPr(callingUid)
19378                        < Build.VERSION_CODES.FROYO) {
19379                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19380                            + Binder.getCallingUid());
19381                    return;
19382                }
19383                mContext.enforceCallingOrSelfPermission(
19384                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19385            }
19386
19387            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19388            if (pir != null) {
19389                // Get all of the existing entries that exactly match this filter.
19390                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19391                if (existing != null && existing.size() == 1) {
19392                    PreferredActivity cur = existing.get(0);
19393                    if (DEBUG_PREFERRED) {
19394                        Slog.i(TAG, "Checking replace of preferred:");
19395                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19396                        if (!cur.mPref.mAlways) {
19397                            Slog.i(TAG, "  -- CUR; not mAlways!");
19398                        } else {
19399                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19400                            Slog.i(TAG, "  -- CUR: mSet="
19401                                    + Arrays.toString(cur.mPref.mSetComponents));
19402                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19403                            Slog.i(TAG, "  -- NEW: mMatch="
19404                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19405                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19406                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19407                        }
19408                    }
19409                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19410                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19411                            && cur.mPref.sameSet(set)) {
19412                        // Setting the preferred activity to what it happens to be already
19413                        if (DEBUG_PREFERRED) {
19414                            Slog.i(TAG, "Replacing with same preferred activity "
19415                                    + cur.mPref.mShortComponent + " for user "
19416                                    + userId + ":");
19417                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19418                        }
19419                        return;
19420                    }
19421                }
19422
19423                if (existing != null) {
19424                    if (DEBUG_PREFERRED) {
19425                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19426                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19427                    }
19428                    for (int i = 0; i < existing.size(); i++) {
19429                        PreferredActivity pa = existing.get(i);
19430                        if (DEBUG_PREFERRED) {
19431                            Slog.i(TAG, "Removing existing preferred activity "
19432                                    + pa.mPref.mComponent + ":");
19433                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19434                        }
19435                        pir.removeFilter(pa);
19436                    }
19437                }
19438            }
19439            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19440                    "Replacing preferred");
19441        }
19442    }
19443
19444    @Override
19445    public void clearPackagePreferredActivities(String packageName) {
19446        final int callingUid = Binder.getCallingUid();
19447        if (getInstantAppPackageName(callingUid) != null) {
19448            return;
19449        }
19450        // writer
19451        synchronized (mPackages) {
19452            PackageParser.Package pkg = mPackages.get(packageName);
19453            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19454                if (mContext.checkCallingOrSelfPermission(
19455                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19456                        != PackageManager.PERMISSION_GRANTED) {
19457                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19458                            < Build.VERSION_CODES.FROYO) {
19459                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19460                                + callingUid);
19461                        return;
19462                    }
19463                    mContext.enforceCallingOrSelfPermission(
19464                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19465                }
19466            }
19467            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19468            if (ps != null
19469                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19470                return;
19471            }
19472            int user = UserHandle.getCallingUserId();
19473            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19474                scheduleWritePackageRestrictionsLocked(user);
19475            }
19476        }
19477    }
19478
19479    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19480    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19481        ArrayList<PreferredActivity> removed = null;
19482        boolean changed = false;
19483        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19484            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19485            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19486            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19487                continue;
19488            }
19489            Iterator<PreferredActivity> it = pir.filterIterator();
19490            while (it.hasNext()) {
19491                PreferredActivity pa = it.next();
19492                // Mark entry for removal only if it matches the package name
19493                // and the entry is of type "always".
19494                if (packageName == null ||
19495                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19496                                && pa.mPref.mAlways)) {
19497                    if (removed == null) {
19498                        removed = new ArrayList<PreferredActivity>();
19499                    }
19500                    removed.add(pa);
19501                }
19502            }
19503            if (removed != null) {
19504                for (int j=0; j<removed.size(); j++) {
19505                    PreferredActivity pa = removed.get(j);
19506                    pir.removeFilter(pa);
19507                }
19508                changed = true;
19509            }
19510        }
19511        if (changed) {
19512            postPreferredActivityChangedBroadcast(userId);
19513        }
19514        return changed;
19515    }
19516
19517    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19518    private void clearIntentFilterVerificationsLPw(int userId) {
19519        final int packageCount = mPackages.size();
19520        for (int i = 0; i < packageCount; i++) {
19521            PackageParser.Package pkg = mPackages.valueAt(i);
19522            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19523        }
19524    }
19525
19526    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19527    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19528        if (userId == UserHandle.USER_ALL) {
19529            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19530                    sUserManager.getUserIds())) {
19531                for (int oneUserId : sUserManager.getUserIds()) {
19532                    scheduleWritePackageRestrictionsLocked(oneUserId);
19533                }
19534            }
19535        } else {
19536            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19537                scheduleWritePackageRestrictionsLocked(userId);
19538            }
19539        }
19540    }
19541
19542    /** Clears state for all users, and touches intent filter verification policy */
19543    void clearDefaultBrowserIfNeeded(String packageName) {
19544        for (int oneUserId : sUserManager.getUserIds()) {
19545            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19546        }
19547    }
19548
19549    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19550        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19551        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19552            if (packageName.equals(defaultBrowserPackageName)) {
19553                setDefaultBrowserPackageName(null, userId);
19554            }
19555        }
19556    }
19557
19558    @Override
19559    public void resetApplicationPreferences(int userId) {
19560        mContext.enforceCallingOrSelfPermission(
19561                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19562        final long identity = Binder.clearCallingIdentity();
19563        // writer
19564        try {
19565            synchronized (mPackages) {
19566                clearPackagePreferredActivitiesLPw(null, userId);
19567                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19568                // TODO: We have to reset the default SMS and Phone. This requires
19569                // significant refactoring to keep all default apps in the package
19570                // manager (cleaner but more work) or have the services provide
19571                // callbacks to the package manager to request a default app reset.
19572                applyFactoryDefaultBrowserLPw(userId);
19573                clearIntentFilterVerificationsLPw(userId);
19574                primeDomainVerificationsLPw(userId);
19575                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19576                scheduleWritePackageRestrictionsLocked(userId);
19577            }
19578            resetNetworkPolicies(userId);
19579        } finally {
19580            Binder.restoreCallingIdentity(identity);
19581        }
19582    }
19583
19584    @Override
19585    public int getPreferredActivities(List<IntentFilter> outFilters,
19586            List<ComponentName> outActivities, String packageName) {
19587        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19588            return 0;
19589        }
19590        int num = 0;
19591        final int userId = UserHandle.getCallingUserId();
19592        // reader
19593        synchronized (mPackages) {
19594            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19595            if (pir != null) {
19596                final Iterator<PreferredActivity> it = pir.filterIterator();
19597                while (it.hasNext()) {
19598                    final PreferredActivity pa = it.next();
19599                    if (packageName == null
19600                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19601                                    && pa.mPref.mAlways)) {
19602                        if (outFilters != null) {
19603                            outFilters.add(new IntentFilter(pa));
19604                        }
19605                        if (outActivities != null) {
19606                            outActivities.add(pa.mPref.mComponent);
19607                        }
19608                    }
19609                }
19610            }
19611        }
19612
19613        return num;
19614    }
19615
19616    @Override
19617    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19618            int userId) {
19619        int callingUid = Binder.getCallingUid();
19620        if (callingUid != Process.SYSTEM_UID) {
19621            throw new SecurityException(
19622                    "addPersistentPreferredActivity can only be run by the system");
19623        }
19624        if (filter.countActions() == 0) {
19625            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19626            return;
19627        }
19628        synchronized (mPackages) {
19629            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19630                    ":");
19631            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19632            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19633                    new PersistentPreferredActivity(filter, activity));
19634            scheduleWritePackageRestrictionsLocked(userId);
19635            postPreferredActivityChangedBroadcast(userId);
19636        }
19637    }
19638
19639    @Override
19640    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19641        int callingUid = Binder.getCallingUid();
19642        if (callingUid != Process.SYSTEM_UID) {
19643            throw new SecurityException(
19644                    "clearPackagePersistentPreferredActivities can only be run by the system");
19645        }
19646        ArrayList<PersistentPreferredActivity> removed = null;
19647        boolean changed = false;
19648        synchronized (mPackages) {
19649            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19650                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19651                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19652                        .valueAt(i);
19653                if (userId != thisUserId) {
19654                    continue;
19655                }
19656                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19657                while (it.hasNext()) {
19658                    PersistentPreferredActivity ppa = it.next();
19659                    // Mark entry for removal only if it matches the package name.
19660                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19661                        if (removed == null) {
19662                            removed = new ArrayList<PersistentPreferredActivity>();
19663                        }
19664                        removed.add(ppa);
19665                    }
19666                }
19667                if (removed != null) {
19668                    for (int j=0; j<removed.size(); j++) {
19669                        PersistentPreferredActivity ppa = removed.get(j);
19670                        ppir.removeFilter(ppa);
19671                    }
19672                    changed = true;
19673                }
19674            }
19675
19676            if (changed) {
19677                scheduleWritePackageRestrictionsLocked(userId);
19678                postPreferredActivityChangedBroadcast(userId);
19679            }
19680        }
19681    }
19682
19683    /**
19684     * Common machinery for picking apart a restored XML blob and passing
19685     * it to a caller-supplied functor to be applied to the running system.
19686     */
19687    private void restoreFromXml(XmlPullParser parser, int userId,
19688            String expectedStartTag, BlobXmlRestorer functor)
19689            throws IOException, XmlPullParserException {
19690        int type;
19691        while ((type = parser.next()) != XmlPullParser.START_TAG
19692                && type != XmlPullParser.END_DOCUMENT) {
19693        }
19694        if (type != XmlPullParser.START_TAG) {
19695            // oops didn't find a start tag?!
19696            if (DEBUG_BACKUP) {
19697                Slog.e(TAG, "Didn't find start tag during restore");
19698            }
19699            return;
19700        }
19701Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19702        // this is supposed to be TAG_PREFERRED_BACKUP
19703        if (!expectedStartTag.equals(parser.getName())) {
19704            if (DEBUG_BACKUP) {
19705                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19706            }
19707            return;
19708        }
19709
19710        // skip interfering stuff, then we're aligned with the backing implementation
19711        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19712Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19713        functor.apply(parser, userId);
19714    }
19715
19716    private interface BlobXmlRestorer {
19717        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19718    }
19719
19720    /**
19721     * Non-Binder method, support for the backup/restore mechanism: write the
19722     * full set of preferred activities in its canonical XML format.  Returns the
19723     * XML output as a byte array, or null if there is none.
19724     */
19725    @Override
19726    public byte[] getPreferredActivityBackup(int userId) {
19727        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19728            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19729        }
19730
19731        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19732        try {
19733            final XmlSerializer serializer = new FastXmlSerializer();
19734            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19735            serializer.startDocument(null, true);
19736            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19737
19738            synchronized (mPackages) {
19739                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19740            }
19741
19742            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19743            serializer.endDocument();
19744            serializer.flush();
19745        } catch (Exception e) {
19746            if (DEBUG_BACKUP) {
19747                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19748            }
19749            return null;
19750        }
19751
19752        return dataStream.toByteArray();
19753    }
19754
19755    @Override
19756    public void restorePreferredActivities(byte[] backup, int userId) {
19757        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19758            throw new SecurityException("Only the system may call restorePreferredActivities()");
19759        }
19760
19761        try {
19762            final XmlPullParser parser = Xml.newPullParser();
19763            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19764            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19765                    new BlobXmlRestorer() {
19766                        @Override
19767                        public void apply(XmlPullParser parser, int userId)
19768                                throws XmlPullParserException, IOException {
19769                            synchronized (mPackages) {
19770                                mSettings.readPreferredActivitiesLPw(parser, userId);
19771                            }
19772                        }
19773                    } );
19774        } catch (Exception e) {
19775            if (DEBUG_BACKUP) {
19776                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19777            }
19778        }
19779    }
19780
19781    /**
19782     * Non-Binder method, support for the backup/restore mechanism: write the
19783     * default browser (etc) settings in its canonical XML format.  Returns the default
19784     * browser XML representation as a byte array, or null if there is none.
19785     */
19786    @Override
19787    public byte[] getDefaultAppsBackup(int userId) {
19788        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19789            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19790        }
19791
19792        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19793        try {
19794            final XmlSerializer serializer = new FastXmlSerializer();
19795            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19796            serializer.startDocument(null, true);
19797            serializer.startTag(null, TAG_DEFAULT_APPS);
19798
19799            synchronized (mPackages) {
19800                mSettings.writeDefaultAppsLPr(serializer, userId);
19801            }
19802
19803            serializer.endTag(null, TAG_DEFAULT_APPS);
19804            serializer.endDocument();
19805            serializer.flush();
19806        } catch (Exception e) {
19807            if (DEBUG_BACKUP) {
19808                Slog.e(TAG, "Unable to write default apps for backup", e);
19809            }
19810            return null;
19811        }
19812
19813        return dataStream.toByteArray();
19814    }
19815
19816    @Override
19817    public void restoreDefaultApps(byte[] backup, int userId) {
19818        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19819            throw new SecurityException("Only the system may call restoreDefaultApps()");
19820        }
19821
19822        try {
19823            final XmlPullParser parser = Xml.newPullParser();
19824            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19825            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19826                    new BlobXmlRestorer() {
19827                        @Override
19828                        public void apply(XmlPullParser parser, int userId)
19829                                throws XmlPullParserException, IOException {
19830                            synchronized (mPackages) {
19831                                mSettings.readDefaultAppsLPw(parser, userId);
19832                            }
19833                        }
19834                    } );
19835        } catch (Exception e) {
19836            if (DEBUG_BACKUP) {
19837                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19838            }
19839        }
19840    }
19841
19842    @Override
19843    public byte[] getIntentFilterVerificationBackup(int userId) {
19844        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19845            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19846        }
19847
19848        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19849        try {
19850            final XmlSerializer serializer = new FastXmlSerializer();
19851            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19852            serializer.startDocument(null, true);
19853            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19854
19855            synchronized (mPackages) {
19856                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19857            }
19858
19859            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19860            serializer.endDocument();
19861            serializer.flush();
19862        } catch (Exception e) {
19863            if (DEBUG_BACKUP) {
19864                Slog.e(TAG, "Unable to write default apps for backup", e);
19865            }
19866            return null;
19867        }
19868
19869        return dataStream.toByteArray();
19870    }
19871
19872    @Override
19873    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19874        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19875            throw new SecurityException("Only the system may call restorePreferredActivities()");
19876        }
19877
19878        try {
19879            final XmlPullParser parser = Xml.newPullParser();
19880            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19881            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19882                    new BlobXmlRestorer() {
19883                        @Override
19884                        public void apply(XmlPullParser parser, int userId)
19885                                throws XmlPullParserException, IOException {
19886                            synchronized (mPackages) {
19887                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19888                                mSettings.writeLPr();
19889                            }
19890                        }
19891                    } );
19892        } catch (Exception e) {
19893            if (DEBUG_BACKUP) {
19894                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19895            }
19896        }
19897    }
19898
19899    @Override
19900    public byte[] getPermissionGrantBackup(int userId) {
19901        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19902            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19903        }
19904
19905        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19906        try {
19907            final XmlSerializer serializer = new FastXmlSerializer();
19908            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19909            serializer.startDocument(null, true);
19910            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19911
19912            synchronized (mPackages) {
19913                serializeRuntimePermissionGrantsLPr(serializer, userId);
19914            }
19915
19916            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19917            serializer.endDocument();
19918            serializer.flush();
19919        } catch (Exception e) {
19920            if (DEBUG_BACKUP) {
19921                Slog.e(TAG, "Unable to write default apps for backup", e);
19922            }
19923            return null;
19924        }
19925
19926        return dataStream.toByteArray();
19927    }
19928
19929    @Override
19930    public void restorePermissionGrants(byte[] backup, int userId) {
19931        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19932            throw new SecurityException("Only the system may call restorePermissionGrants()");
19933        }
19934
19935        try {
19936            final XmlPullParser parser = Xml.newPullParser();
19937            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19938            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19939                    new BlobXmlRestorer() {
19940                        @Override
19941                        public void apply(XmlPullParser parser, int userId)
19942                                throws XmlPullParserException, IOException {
19943                            synchronized (mPackages) {
19944                                processRestoredPermissionGrantsLPr(parser, userId);
19945                            }
19946                        }
19947                    } );
19948        } catch (Exception e) {
19949            if (DEBUG_BACKUP) {
19950                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19951            }
19952        }
19953    }
19954
19955    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19956            throws IOException {
19957        serializer.startTag(null, TAG_ALL_GRANTS);
19958
19959        final int N = mSettings.mPackages.size();
19960        for (int i = 0; i < N; i++) {
19961            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19962            boolean pkgGrantsKnown = false;
19963
19964            PermissionsState packagePerms = ps.getPermissionsState();
19965
19966            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19967                final int grantFlags = state.getFlags();
19968                // only look at grants that are not system/policy fixed
19969                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19970                    final boolean isGranted = state.isGranted();
19971                    // And only back up the user-twiddled state bits
19972                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19973                        final String packageName = mSettings.mPackages.keyAt(i);
19974                        if (!pkgGrantsKnown) {
19975                            serializer.startTag(null, TAG_GRANT);
19976                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19977                            pkgGrantsKnown = true;
19978                        }
19979
19980                        final boolean userSet =
19981                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19982                        final boolean userFixed =
19983                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19984                        final boolean revoke =
19985                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19986
19987                        serializer.startTag(null, TAG_PERMISSION);
19988                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19989                        if (isGranted) {
19990                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19991                        }
19992                        if (userSet) {
19993                            serializer.attribute(null, ATTR_USER_SET, "true");
19994                        }
19995                        if (userFixed) {
19996                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19997                        }
19998                        if (revoke) {
19999                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20000                        }
20001                        serializer.endTag(null, TAG_PERMISSION);
20002                    }
20003                }
20004            }
20005
20006            if (pkgGrantsKnown) {
20007                serializer.endTag(null, TAG_GRANT);
20008            }
20009        }
20010
20011        serializer.endTag(null, TAG_ALL_GRANTS);
20012    }
20013
20014    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20015            throws XmlPullParserException, IOException {
20016        String pkgName = null;
20017        int outerDepth = parser.getDepth();
20018        int type;
20019        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20020                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20021            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20022                continue;
20023            }
20024
20025            final String tagName = parser.getName();
20026            if (tagName.equals(TAG_GRANT)) {
20027                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20028                if (DEBUG_BACKUP) {
20029                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20030                }
20031            } else if (tagName.equals(TAG_PERMISSION)) {
20032
20033                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20034                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20035
20036                int newFlagSet = 0;
20037                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20038                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20039                }
20040                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20041                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20042                }
20043                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20044                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20045                }
20046                if (DEBUG_BACKUP) {
20047                    Slog.v(TAG, "  + Restoring grant:"
20048                            + " pkg=" + pkgName
20049                            + " perm=" + permName
20050                            + " granted=" + isGranted
20051                            + " bits=0x" + Integer.toHexString(newFlagSet));
20052                }
20053                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20054                if (ps != null) {
20055                    // Already installed so we apply the grant immediately
20056                    if (DEBUG_BACKUP) {
20057                        Slog.v(TAG, "        + already installed; applying");
20058                    }
20059                    PermissionsState perms = ps.getPermissionsState();
20060                    BasePermission bp =
20061                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20062                    if (bp != null) {
20063                        if (isGranted) {
20064                            perms.grantRuntimePermission(bp, userId);
20065                        }
20066                        if (newFlagSet != 0) {
20067                            perms.updatePermissionFlags(
20068                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20069                        }
20070                    }
20071                } else {
20072                    // Need to wait for post-restore install to apply the grant
20073                    if (DEBUG_BACKUP) {
20074                        Slog.v(TAG, "        - not yet installed; saving for later");
20075                    }
20076                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20077                            isGranted, newFlagSet, userId);
20078                }
20079            } else {
20080                PackageManagerService.reportSettingsProblem(Log.WARN,
20081                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20082                XmlUtils.skipCurrentTag(parser);
20083            }
20084        }
20085
20086        scheduleWriteSettingsLocked();
20087        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20088    }
20089
20090    @Override
20091    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20092            int sourceUserId, int targetUserId, int flags) {
20093        mContext.enforceCallingOrSelfPermission(
20094                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20095        int callingUid = Binder.getCallingUid();
20096        enforceOwnerRights(ownerPackage, callingUid);
20097        PackageManagerServiceUtils.enforceShellRestriction(
20098                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20099        if (intentFilter.countActions() == 0) {
20100            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20101            return;
20102        }
20103        synchronized (mPackages) {
20104            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20105                    ownerPackage, targetUserId, flags);
20106            CrossProfileIntentResolver resolver =
20107                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20108            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20109            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20110            if (existing != null) {
20111                int size = existing.size();
20112                for (int i = 0; i < size; i++) {
20113                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20114                        return;
20115                    }
20116                }
20117            }
20118            resolver.addFilter(newFilter);
20119            scheduleWritePackageRestrictionsLocked(sourceUserId);
20120        }
20121    }
20122
20123    @Override
20124    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20125        mContext.enforceCallingOrSelfPermission(
20126                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20127        final int callingUid = Binder.getCallingUid();
20128        enforceOwnerRights(ownerPackage, callingUid);
20129        PackageManagerServiceUtils.enforceShellRestriction(
20130                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20131        synchronized (mPackages) {
20132            CrossProfileIntentResolver resolver =
20133                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20134            ArraySet<CrossProfileIntentFilter> set =
20135                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20136            for (CrossProfileIntentFilter filter : set) {
20137                if (filter.getOwnerPackage().equals(ownerPackage)) {
20138                    resolver.removeFilter(filter);
20139                }
20140            }
20141            scheduleWritePackageRestrictionsLocked(sourceUserId);
20142        }
20143    }
20144
20145    // Enforcing that callingUid is owning pkg on userId
20146    private void enforceOwnerRights(String pkg, int callingUid) {
20147        // The system owns everything.
20148        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20149            return;
20150        }
20151        final int callingUserId = UserHandle.getUserId(callingUid);
20152        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20153        if (pi == null) {
20154            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20155                    + callingUserId);
20156        }
20157        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20158            throw new SecurityException("Calling uid " + callingUid
20159                    + " does not own package " + pkg);
20160        }
20161    }
20162
20163    @Override
20164    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20165        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20166            return null;
20167        }
20168        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20169    }
20170
20171    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20172        UserManagerService ums = UserManagerService.getInstance();
20173        if (ums != null) {
20174            final UserInfo parent = ums.getProfileParent(userId);
20175            final int launcherUid = (parent != null) ? parent.id : userId;
20176            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20177            if (launcherComponent != null) {
20178                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20179                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20180                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20181                        .setPackage(launcherComponent.getPackageName());
20182                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20183            }
20184        }
20185    }
20186
20187    /**
20188     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20189     * then reports the most likely home activity or null if there are more than one.
20190     */
20191    private ComponentName getDefaultHomeActivity(int userId) {
20192        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20193        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20194        if (cn != null) {
20195            return cn;
20196        }
20197
20198        // Find the launcher with the highest priority and return that component if there are no
20199        // other home activity with the same priority.
20200        int lastPriority = Integer.MIN_VALUE;
20201        ComponentName lastComponent = null;
20202        final int size = allHomeCandidates.size();
20203        for (int i = 0; i < size; i++) {
20204            final ResolveInfo ri = allHomeCandidates.get(i);
20205            if (ri.priority > lastPriority) {
20206                lastComponent = ri.activityInfo.getComponentName();
20207                lastPriority = ri.priority;
20208            } else if (ri.priority == lastPriority) {
20209                // Two components found with same priority.
20210                lastComponent = null;
20211            }
20212        }
20213        return lastComponent;
20214    }
20215
20216    private Intent getHomeIntent() {
20217        Intent intent = new Intent(Intent.ACTION_MAIN);
20218        intent.addCategory(Intent.CATEGORY_HOME);
20219        intent.addCategory(Intent.CATEGORY_DEFAULT);
20220        return intent;
20221    }
20222
20223    private IntentFilter getHomeFilter() {
20224        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20225        filter.addCategory(Intent.CATEGORY_HOME);
20226        filter.addCategory(Intent.CATEGORY_DEFAULT);
20227        return filter;
20228    }
20229
20230    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20231            int userId) {
20232        Intent intent  = getHomeIntent();
20233        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20234                PackageManager.GET_META_DATA, userId);
20235        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20236                true, false, false, userId);
20237
20238        allHomeCandidates.clear();
20239        if (list != null) {
20240            for (ResolveInfo ri : list) {
20241                allHomeCandidates.add(ri);
20242            }
20243        }
20244        return (preferred == null || preferred.activityInfo == null)
20245                ? null
20246                : new ComponentName(preferred.activityInfo.packageName,
20247                        preferred.activityInfo.name);
20248    }
20249
20250    @Override
20251    public void setHomeActivity(ComponentName comp, int userId) {
20252        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20253            return;
20254        }
20255        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20256        getHomeActivitiesAsUser(homeActivities, userId);
20257
20258        boolean found = false;
20259
20260        final int size = homeActivities.size();
20261        final ComponentName[] set = new ComponentName[size];
20262        for (int i = 0; i < size; i++) {
20263            final ResolveInfo candidate = homeActivities.get(i);
20264            final ActivityInfo info = candidate.activityInfo;
20265            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20266            set[i] = activityName;
20267            if (!found && activityName.equals(comp)) {
20268                found = true;
20269            }
20270        }
20271        if (!found) {
20272            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20273                    + userId);
20274        }
20275        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20276                set, comp, userId);
20277    }
20278
20279    private @Nullable String getSetupWizardPackageName() {
20280        final Intent intent = new Intent(Intent.ACTION_MAIN);
20281        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20282
20283        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20284                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20285                        | MATCH_DISABLED_COMPONENTS,
20286                UserHandle.myUserId());
20287        if (matches.size() == 1) {
20288            return matches.get(0).getComponentInfo().packageName;
20289        } else {
20290            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20291                    + ": matches=" + matches);
20292            return null;
20293        }
20294    }
20295
20296    private @Nullable String getStorageManagerPackageName() {
20297        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20298
20299        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20300                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20301                        | MATCH_DISABLED_COMPONENTS,
20302                UserHandle.myUserId());
20303        if (matches.size() == 1) {
20304            return matches.get(0).getComponentInfo().packageName;
20305        } else {
20306            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20307                    + matches.size() + ": matches=" + matches);
20308            return null;
20309        }
20310    }
20311
20312    @Override
20313    public String getSystemTextClassifierPackageName() {
20314        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20315    }
20316
20317    @Override
20318    public void setApplicationEnabledSetting(String appPackageName,
20319            int newState, int flags, int userId, String callingPackage) {
20320        if (!sUserManager.exists(userId)) return;
20321        if (callingPackage == null) {
20322            callingPackage = Integer.toString(Binder.getCallingUid());
20323        }
20324        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20325    }
20326
20327    @Override
20328    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20329        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20330        synchronized (mPackages) {
20331            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20332            if (pkgSetting != null) {
20333                pkgSetting.setUpdateAvailable(updateAvailable);
20334            }
20335        }
20336    }
20337
20338    @Override
20339    public void setComponentEnabledSetting(ComponentName componentName,
20340            int newState, int flags, int userId) {
20341        if (!sUserManager.exists(userId)) return;
20342        setEnabledSetting(componentName.getPackageName(),
20343                componentName.getClassName(), newState, flags, userId, null);
20344    }
20345
20346    private void setEnabledSetting(final String packageName, String className, int newState,
20347            final int flags, int userId, String callingPackage) {
20348        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20349              || newState == COMPONENT_ENABLED_STATE_ENABLED
20350              || newState == COMPONENT_ENABLED_STATE_DISABLED
20351              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20352              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20353            throw new IllegalArgumentException("Invalid new component state: "
20354                    + newState);
20355        }
20356        PackageSetting pkgSetting;
20357        final int callingUid = Binder.getCallingUid();
20358        final int permission;
20359        if (callingUid == Process.SYSTEM_UID) {
20360            permission = PackageManager.PERMISSION_GRANTED;
20361        } else {
20362            permission = mContext.checkCallingOrSelfPermission(
20363                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20364        }
20365        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20366                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20367        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20368        boolean sendNow = false;
20369        boolean isApp = (className == null);
20370        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20371        String componentName = isApp ? packageName : className;
20372        int packageUid = -1;
20373        ArrayList<String> components;
20374
20375        // reader
20376        synchronized (mPackages) {
20377            pkgSetting = mSettings.mPackages.get(packageName);
20378            if (pkgSetting == null) {
20379                if (!isCallerInstantApp) {
20380                    if (className == null) {
20381                        throw new IllegalArgumentException("Unknown package: " + packageName);
20382                    }
20383                    throw new IllegalArgumentException(
20384                            "Unknown component: " + packageName + "/" + className);
20385                } else {
20386                    // throw SecurityException to prevent leaking package information
20387                    throw new SecurityException(
20388                            "Attempt to change component state; "
20389                            + "pid=" + Binder.getCallingPid()
20390                            + ", uid=" + callingUid
20391                            + (className == null
20392                                    ? ", package=" + packageName
20393                                    : ", component=" + packageName + "/" + className));
20394                }
20395            }
20396        }
20397
20398        // Limit who can change which apps
20399        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20400            // Don't allow apps that don't have permission to modify other apps
20401            if (!allowedByPermission
20402                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20403                throw new SecurityException(
20404                        "Attempt to change component state; "
20405                        + "pid=" + Binder.getCallingPid()
20406                        + ", uid=" + callingUid
20407                        + (className == null
20408                                ? ", package=" + packageName
20409                                : ", component=" + packageName + "/" + className));
20410            }
20411            // Don't allow changing protected packages.
20412            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20413                throw new SecurityException("Cannot disable a protected package: " + packageName);
20414            }
20415        }
20416
20417        synchronized (mPackages) {
20418            if (callingUid == Process.SHELL_UID
20419                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20420                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20421                // unless it is a test package.
20422                int oldState = pkgSetting.getEnabled(userId);
20423                if (className == null
20424                        &&
20425                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20426                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20427                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20428                        &&
20429                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20430                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20431                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20432                    // ok
20433                } else {
20434                    throw new SecurityException(
20435                            "Shell cannot change component state for " + packageName + "/"
20436                                    + className + " to " + newState);
20437                }
20438            }
20439        }
20440        if (className == null) {
20441            // We're dealing with an application/package level state change
20442            synchronized (mPackages) {
20443                if (pkgSetting.getEnabled(userId) == newState) {
20444                    // Nothing to do
20445                    return;
20446                }
20447            }
20448            // If we're enabling a system stub, there's a little more work to do.
20449            // Prior to enabling the package, we need to decompress the APK(s) to the
20450            // data partition and then replace the version on the system partition.
20451            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20452            final boolean isSystemStub = deletedPkg.isStub
20453                    && deletedPkg.isSystem();
20454            if (isSystemStub
20455                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20456                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20457                final File codePath = decompressPackage(deletedPkg);
20458                if (codePath == null) {
20459                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20460                    return;
20461                }
20462                // TODO remove direct parsing of the package object during internal cleanup
20463                // of scan package
20464                // We need to call parse directly here for no other reason than we need
20465                // the new package in order to disable the old one [we use the information
20466                // for some internal optimization to optionally create a new package setting
20467                // object on replace]. However, we can't get the package from the scan
20468                // because the scan modifies live structures and we need to remove the
20469                // old [system] package from the system before a scan can be attempted.
20470                // Once scan is indempotent we can remove this parse and use the package
20471                // object we scanned, prior to adding it to package settings.
20472                final PackageParser pp = new PackageParser();
20473                pp.setSeparateProcesses(mSeparateProcesses);
20474                pp.setDisplayMetrics(mMetrics);
20475                pp.setCallback(mPackageParserCallback);
20476                final PackageParser.Package tmpPkg;
20477                try {
20478                    final @ParseFlags int parseFlags = mDefParseFlags
20479                            | PackageParser.PARSE_MUST_BE_APK
20480                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20481                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20482                } catch (PackageParserException e) {
20483                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20484                    return;
20485                }
20486                synchronized (mInstallLock) {
20487                    // Disable the stub and remove any package entries
20488                    removePackageLI(deletedPkg, true);
20489                    synchronized (mPackages) {
20490                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20491                    }
20492                    final PackageParser.Package pkg;
20493                    try (PackageFreezer freezer =
20494                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20495                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20496                                | PackageParser.PARSE_ENFORCE_CODE;
20497                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20498                                0 /*currentTime*/, null /*user*/);
20499                        prepareAppDataAfterInstallLIF(pkg);
20500                        synchronized (mPackages) {
20501                            try {
20502                                updateSharedLibrariesLPr(pkg, null);
20503                            } catch (PackageManagerException e) {
20504                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20505                            }
20506                            mPermissionManager.updatePermissions(
20507                                    pkg.packageName, pkg, true, mPackages.values(),
20508                                    mPermissionCallback);
20509                            mSettings.writeLPr();
20510                        }
20511                    } catch (PackageManagerException e) {
20512                        // Whoops! Something went wrong; try to roll back to the stub
20513                        Slog.w(TAG, "Failed to install compressed system package:"
20514                                + pkgSetting.name, e);
20515                        // Remove the failed install
20516                        removeCodePathLI(codePath);
20517
20518                        // Install the system package
20519                        try (PackageFreezer freezer =
20520                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20521                            synchronized (mPackages) {
20522                                // NOTE: The system package always needs to be enabled; even
20523                                // if it's for a compressed stub. If we don't, installing the
20524                                // system package fails during scan [scanning checks the disabled
20525                                // packages]. We will reverse this later, after we've "installed"
20526                                // the stub.
20527                                // This leaves us in a fragile state; the stub should never be
20528                                // enabled, so, cross your fingers and hope nothing goes wrong
20529                                // until we can disable the package later.
20530                                enableSystemPackageLPw(deletedPkg);
20531                            }
20532                            installPackageFromSystemLIF(deletedPkg.codePath,
20533                                    false /*isPrivileged*/, null /*allUserHandles*/,
20534                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20535                                    true /*writeSettings*/);
20536                        } catch (PackageManagerException pme) {
20537                            Slog.w(TAG, "Failed to restore system package:"
20538                                    + deletedPkg.packageName, pme);
20539                        } finally {
20540                            synchronized (mPackages) {
20541                                mSettings.disableSystemPackageLPw(
20542                                        deletedPkg.packageName, true /*replaced*/);
20543                                mSettings.writeLPr();
20544                            }
20545                        }
20546                        return;
20547                    }
20548                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20549                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20550                    mDexManager.notifyPackageUpdated(pkg.packageName,
20551                            pkg.baseCodePath, pkg.splitCodePaths);
20552                }
20553            }
20554            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20555                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20556                // Don't care about who enables an app.
20557                callingPackage = null;
20558            }
20559            synchronized (mPackages) {
20560                pkgSetting.setEnabled(newState, userId, callingPackage);
20561            }
20562        } else {
20563            synchronized (mPackages) {
20564                // We're dealing with a component level state change
20565                // First, verify that this is a valid class name.
20566                PackageParser.Package pkg = pkgSetting.pkg;
20567                if (pkg == null || !pkg.hasComponentClassName(className)) {
20568                    if (pkg != null &&
20569                            pkg.applicationInfo.targetSdkVersion >=
20570                                    Build.VERSION_CODES.JELLY_BEAN) {
20571                        throw new IllegalArgumentException("Component class " + className
20572                                + " does not exist in " + packageName);
20573                    } else {
20574                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20575                                + className + " does not exist in " + packageName);
20576                    }
20577                }
20578                switch (newState) {
20579                    case COMPONENT_ENABLED_STATE_ENABLED:
20580                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20581                            return;
20582                        }
20583                        break;
20584                    case COMPONENT_ENABLED_STATE_DISABLED:
20585                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20586                            return;
20587                        }
20588                        break;
20589                    case COMPONENT_ENABLED_STATE_DEFAULT:
20590                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20591                            return;
20592                        }
20593                        break;
20594                    default:
20595                        Slog.e(TAG, "Invalid new component state: " + newState);
20596                        return;
20597                }
20598            }
20599        }
20600        synchronized (mPackages) {
20601            scheduleWritePackageRestrictionsLocked(userId);
20602            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20603            final long callingId = Binder.clearCallingIdentity();
20604            try {
20605                updateInstantAppInstallerLocked(packageName);
20606            } finally {
20607                Binder.restoreCallingIdentity(callingId);
20608            }
20609            components = mPendingBroadcasts.get(userId, packageName);
20610            final boolean newPackage = components == null;
20611            if (newPackage) {
20612                components = new ArrayList<String>();
20613            }
20614            if (!components.contains(componentName)) {
20615                components.add(componentName);
20616            }
20617            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20618                sendNow = true;
20619                // Purge entry from pending broadcast list if another one exists already
20620                // since we are sending one right away.
20621                mPendingBroadcasts.remove(userId, packageName);
20622            } else {
20623                if (newPackage) {
20624                    mPendingBroadcasts.put(userId, packageName, components);
20625                }
20626                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20627                    // Schedule a message
20628                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20629                }
20630            }
20631        }
20632
20633        long callingId = Binder.clearCallingIdentity();
20634        try {
20635            if (sendNow) {
20636                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20637                sendPackageChangedBroadcast(packageName,
20638                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20639            }
20640        } finally {
20641            Binder.restoreCallingIdentity(callingId);
20642        }
20643    }
20644
20645    @Override
20646    public void flushPackageRestrictionsAsUser(int userId) {
20647        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20648            return;
20649        }
20650        if (!sUserManager.exists(userId)) {
20651            return;
20652        }
20653        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20654                false /* checkShell */, "flushPackageRestrictions");
20655        synchronized (mPackages) {
20656            mSettings.writePackageRestrictionsLPr(userId);
20657            mDirtyUsers.remove(userId);
20658            if (mDirtyUsers.isEmpty()) {
20659                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20660            }
20661        }
20662    }
20663
20664    private void sendPackageChangedBroadcast(String packageName,
20665            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20666        if (DEBUG_INSTALL)
20667            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20668                    + componentNames);
20669        Bundle extras = new Bundle(4);
20670        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20671        String nameList[] = new String[componentNames.size()];
20672        componentNames.toArray(nameList);
20673        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20674        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20675        extras.putInt(Intent.EXTRA_UID, packageUid);
20676        // If this is not reporting a change of the overall package, then only send it
20677        // to registered receivers.  We don't want to launch a swath of apps for every
20678        // little component state change.
20679        final int flags = !componentNames.contains(packageName)
20680                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20681        final int userId = UserHandle.getUserId(packageUid);
20682        final boolean isInstantApp = isInstantApp(packageName, userId);
20683        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20684        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20685        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20686                userIds, instantUserIds);
20687    }
20688
20689    @Override
20690    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20691        if (!sUserManager.exists(userId)) return;
20692        final int callingUid = Binder.getCallingUid();
20693        if (getInstantAppPackageName(callingUid) != null) {
20694            return;
20695        }
20696        final int permission = mContext.checkCallingOrSelfPermission(
20697                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20698        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20699        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20700                true /* requireFullPermission */, true /* checkShell */, "stop package");
20701        // writer
20702        synchronized (mPackages) {
20703            final PackageSetting ps = mSettings.mPackages.get(packageName);
20704            if (!filterAppAccessLPr(ps, callingUid, userId)
20705                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20706                            allowedByPermission, callingUid, userId)) {
20707                scheduleWritePackageRestrictionsLocked(userId);
20708            }
20709        }
20710    }
20711
20712    @Override
20713    public String getInstallerPackageName(String packageName) {
20714        final int callingUid = Binder.getCallingUid();
20715        synchronized (mPackages) {
20716            final PackageSetting ps = mSettings.mPackages.get(packageName);
20717            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20718                return null;
20719            }
20720            return mSettings.getInstallerPackageNameLPr(packageName);
20721        }
20722    }
20723
20724    public boolean isOrphaned(String packageName) {
20725        // reader
20726        synchronized (mPackages) {
20727            return mSettings.isOrphaned(packageName);
20728        }
20729    }
20730
20731    @Override
20732    public int getApplicationEnabledSetting(String packageName, int userId) {
20733        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20734        int callingUid = Binder.getCallingUid();
20735        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20736                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20737        // reader
20738        synchronized (mPackages) {
20739            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20740                return COMPONENT_ENABLED_STATE_DISABLED;
20741            }
20742            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20743        }
20744    }
20745
20746    @Override
20747    public int getComponentEnabledSetting(ComponentName component, int userId) {
20748        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20749        int callingUid = Binder.getCallingUid();
20750        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20751                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20752        synchronized (mPackages) {
20753            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20754                    component, TYPE_UNKNOWN, userId)) {
20755                return COMPONENT_ENABLED_STATE_DISABLED;
20756            }
20757            return mSettings.getComponentEnabledSettingLPr(component, userId);
20758        }
20759    }
20760
20761    @Override
20762    public void enterSafeMode() {
20763        enforceSystemOrRoot("Only the system can request entering safe mode");
20764
20765        if (!mSystemReady) {
20766            mSafeMode = true;
20767        }
20768    }
20769
20770    @Override
20771    public void systemReady() {
20772        enforceSystemOrRoot("Only the system can claim the system is ready");
20773
20774        mSystemReady = true;
20775        final ContentResolver resolver = mContext.getContentResolver();
20776        ContentObserver co = new ContentObserver(mHandler) {
20777            @Override
20778            public void onChange(boolean selfChange) {
20779                mWebInstantAppsDisabled =
20780                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20781                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20782            }
20783        };
20784        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20785                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20786                false, co, UserHandle.USER_SYSTEM);
20787        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20788                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20789        co.onChange(true);
20790
20791        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20792        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20793        // it is done.
20794        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20795            @Override
20796            public void onChange(boolean selfChange) {
20797                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20798                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20799                        oobEnabled == 1 ? "true" : "false");
20800            }
20801        };
20802        mContext.getContentResolver().registerContentObserver(
20803                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20804                UserHandle.USER_SYSTEM);
20805        // At boot, restore the value from the setting, which persists across reboot.
20806        privAppOobObserver.onChange(true);
20807
20808        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20809        // disabled after already being started.
20810        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20811                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20812
20813        // Read the compatibilty setting when the system is ready.
20814        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20815                mContext.getContentResolver(),
20816                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20817        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20818        if (DEBUG_SETTINGS) {
20819            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20820        }
20821
20822        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20823
20824        synchronized (mPackages) {
20825            // Verify that all of the preferred activity components actually
20826            // exist.  It is possible for applications to be updated and at
20827            // that point remove a previously declared activity component that
20828            // had been set as a preferred activity.  We try to clean this up
20829            // the next time we encounter that preferred activity, but it is
20830            // possible for the user flow to never be able to return to that
20831            // situation so here we do a sanity check to make sure we haven't
20832            // left any junk around.
20833            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20834            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20835                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20836                removed.clear();
20837                for (PreferredActivity pa : pir.filterSet()) {
20838                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20839                        removed.add(pa);
20840                    }
20841                }
20842                if (removed.size() > 0) {
20843                    for (int r=0; r<removed.size(); r++) {
20844                        PreferredActivity pa = removed.get(r);
20845                        Slog.w(TAG, "Removing dangling preferred activity: "
20846                                + pa.mPref.mComponent);
20847                        pir.removeFilter(pa);
20848                    }
20849                    mSettings.writePackageRestrictionsLPr(
20850                            mSettings.mPreferredActivities.keyAt(i));
20851                }
20852            }
20853
20854            for (int userId : UserManagerService.getInstance().getUserIds()) {
20855                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20856                    grantPermissionsUserIds = ArrayUtils.appendInt(
20857                            grantPermissionsUserIds, userId);
20858                }
20859            }
20860        }
20861        sUserManager.systemReady();
20862        // If we upgraded grant all default permissions before kicking off.
20863        for (int userId : grantPermissionsUserIds) {
20864            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20865        }
20866
20867        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20868            // If we did not grant default permissions, we preload from this the
20869            // default permission exceptions lazily to ensure we don't hit the
20870            // disk on a new user creation.
20871            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20872        }
20873
20874        // Now that we've scanned all packages, and granted any default
20875        // permissions, ensure permissions are updated. Beware of dragons if you
20876        // try optimizing this.
20877        synchronized (mPackages) {
20878            mPermissionManager.updateAllPermissions(
20879                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20880                    mPermissionCallback);
20881        }
20882
20883        // Kick off any messages waiting for system ready
20884        if (mPostSystemReadyMessages != null) {
20885            for (Message msg : mPostSystemReadyMessages) {
20886                msg.sendToTarget();
20887            }
20888            mPostSystemReadyMessages = null;
20889        }
20890
20891        // Watch for external volumes that come and go over time
20892        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20893        storage.registerListener(mStorageListener);
20894
20895        mInstallerService.systemReady();
20896        mPackageDexOptimizer.systemReady();
20897
20898        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20899                StorageManagerInternal.class);
20900        StorageManagerInternal.addExternalStoragePolicy(
20901                new StorageManagerInternal.ExternalStorageMountPolicy() {
20902            @Override
20903            public int getMountMode(int uid, String packageName) {
20904                if (Process.isIsolated(uid)) {
20905                    return Zygote.MOUNT_EXTERNAL_NONE;
20906                }
20907                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20908                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20909                }
20910                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20911                    return Zygote.MOUNT_EXTERNAL_READ;
20912                }
20913                return Zygote.MOUNT_EXTERNAL_WRITE;
20914            }
20915
20916            @Override
20917            public boolean hasExternalStorage(int uid, String packageName) {
20918                return true;
20919            }
20920        });
20921
20922        // Now that we're mostly running, clean up stale users and apps
20923        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20924        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20925
20926        mPermissionManager.systemReady();
20927
20928        if (mInstantAppResolverConnection != null) {
20929            mContext.registerReceiver(new BroadcastReceiver() {
20930                @Override
20931                public void onReceive(Context context, Intent intent) {
20932                    mInstantAppResolverConnection.optimisticBind();
20933                    mContext.unregisterReceiver(this);
20934                }
20935            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
20936        }
20937    }
20938
20939    public void waitForAppDataPrepared() {
20940        if (mPrepareAppDataFuture == null) {
20941            return;
20942        }
20943        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20944        mPrepareAppDataFuture = null;
20945    }
20946
20947    @Override
20948    public boolean isSafeMode() {
20949        // allow instant applications
20950        return mSafeMode;
20951    }
20952
20953    @Override
20954    public boolean hasSystemUidErrors() {
20955        // allow instant applications
20956        return mHasSystemUidErrors;
20957    }
20958
20959    static String arrayToString(int[] array) {
20960        StringBuffer buf = new StringBuffer(128);
20961        buf.append('[');
20962        if (array != null) {
20963            for (int i=0; i<array.length; i++) {
20964                if (i > 0) buf.append(", ");
20965                buf.append(array[i]);
20966            }
20967        }
20968        buf.append(']');
20969        return buf.toString();
20970    }
20971
20972    @Override
20973    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20974            FileDescriptor err, String[] args, ShellCallback callback,
20975            ResultReceiver resultReceiver) {
20976        (new PackageManagerShellCommand(this)).exec(
20977                this, in, out, err, args, callback, resultReceiver);
20978    }
20979
20980    @Override
20981    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20982        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20983
20984        DumpState dumpState = new DumpState();
20985        boolean fullPreferred = false;
20986        boolean checkin = false;
20987
20988        String packageName = null;
20989        ArraySet<String> permissionNames = null;
20990
20991        int opti = 0;
20992        while (opti < args.length) {
20993            String opt = args[opti];
20994            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20995                break;
20996            }
20997            opti++;
20998
20999            if ("-a".equals(opt)) {
21000                // Right now we only know how to print all.
21001            } else if ("-h".equals(opt)) {
21002                pw.println("Package manager dump options:");
21003                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21004                pw.println("    --checkin: dump for a checkin");
21005                pw.println("    -f: print details of intent filters");
21006                pw.println("    -h: print this help");
21007                pw.println("  cmd may be one of:");
21008                pw.println("    l[ibraries]: list known shared libraries");
21009                pw.println("    f[eatures]: list device features");
21010                pw.println("    k[eysets]: print known keysets");
21011                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21012                pw.println("    perm[issions]: dump permissions");
21013                pw.println("    permission [name ...]: dump declaration and use of given permission");
21014                pw.println("    pref[erred]: print preferred package settings");
21015                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21016                pw.println("    prov[iders]: dump content providers");
21017                pw.println("    p[ackages]: dump installed packages");
21018                pw.println("    s[hared-users]: dump shared user IDs");
21019                pw.println("    m[essages]: print collected runtime messages");
21020                pw.println("    v[erifiers]: print package verifier info");
21021                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21022                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21023                pw.println("    version: print database version info");
21024                pw.println("    write: write current settings now");
21025                pw.println("    installs: details about install sessions");
21026                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21027                pw.println("    dexopt: dump dexopt state");
21028                pw.println("    compiler-stats: dump compiler statistics");
21029                pw.println("    service-permissions: dump permissions required by services");
21030                pw.println("    <package.name>: info about given package");
21031                return;
21032            } else if ("--checkin".equals(opt)) {
21033                checkin = true;
21034            } else if ("-f".equals(opt)) {
21035                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21036            } else if ("--proto".equals(opt)) {
21037                dumpProto(fd);
21038                return;
21039            } else {
21040                pw.println("Unknown argument: " + opt + "; use -h for help");
21041            }
21042        }
21043
21044        // Is the caller requesting to dump a particular piece of data?
21045        if (opti < args.length) {
21046            String cmd = args[opti];
21047            opti++;
21048            // Is this a package name?
21049            if ("android".equals(cmd) || cmd.contains(".")) {
21050                packageName = cmd;
21051                // When dumping a single package, we always dump all of its
21052                // filter information since the amount of data will be reasonable.
21053                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21054            } else if ("check-permission".equals(cmd)) {
21055                if (opti >= args.length) {
21056                    pw.println("Error: check-permission missing permission argument");
21057                    return;
21058                }
21059                String perm = args[opti];
21060                opti++;
21061                if (opti >= args.length) {
21062                    pw.println("Error: check-permission missing package argument");
21063                    return;
21064                }
21065
21066                String pkg = args[opti];
21067                opti++;
21068                int user = UserHandle.getUserId(Binder.getCallingUid());
21069                if (opti < args.length) {
21070                    try {
21071                        user = Integer.parseInt(args[opti]);
21072                    } catch (NumberFormatException e) {
21073                        pw.println("Error: check-permission user argument is not a number: "
21074                                + args[opti]);
21075                        return;
21076                    }
21077                }
21078
21079                // Normalize package name to handle renamed packages and static libs
21080                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21081
21082                pw.println(checkPermission(perm, pkg, user));
21083                return;
21084            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21085                dumpState.setDump(DumpState.DUMP_LIBS);
21086            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21087                dumpState.setDump(DumpState.DUMP_FEATURES);
21088            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21089                if (opti >= args.length) {
21090                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21091                            | DumpState.DUMP_SERVICE_RESOLVERS
21092                            | DumpState.DUMP_RECEIVER_RESOLVERS
21093                            | DumpState.DUMP_CONTENT_RESOLVERS);
21094                } else {
21095                    while (opti < args.length) {
21096                        String name = args[opti];
21097                        if ("a".equals(name) || "activity".equals(name)) {
21098                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21099                        } else if ("s".equals(name) || "service".equals(name)) {
21100                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21101                        } else if ("r".equals(name) || "receiver".equals(name)) {
21102                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21103                        } else if ("c".equals(name) || "content".equals(name)) {
21104                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21105                        } else {
21106                            pw.println("Error: unknown resolver table type: " + name);
21107                            return;
21108                        }
21109                        opti++;
21110                    }
21111                }
21112            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21113                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21114            } else if ("permission".equals(cmd)) {
21115                if (opti >= args.length) {
21116                    pw.println("Error: permission requires permission name");
21117                    return;
21118                }
21119                permissionNames = new ArraySet<>();
21120                while (opti < args.length) {
21121                    permissionNames.add(args[opti]);
21122                    opti++;
21123                }
21124                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21125                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21126            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21127                dumpState.setDump(DumpState.DUMP_PREFERRED);
21128            } else if ("preferred-xml".equals(cmd)) {
21129                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21130                if (opti < args.length && "--full".equals(args[opti])) {
21131                    fullPreferred = true;
21132                    opti++;
21133                }
21134            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21135                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21136            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21137                dumpState.setDump(DumpState.DUMP_PACKAGES);
21138            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21139                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21140            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21141                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21142            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21143                dumpState.setDump(DumpState.DUMP_MESSAGES);
21144            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21145                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21146            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21147                    || "intent-filter-verifiers".equals(cmd)) {
21148                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21149            } else if ("version".equals(cmd)) {
21150                dumpState.setDump(DumpState.DUMP_VERSION);
21151            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21152                dumpState.setDump(DumpState.DUMP_KEYSETS);
21153            } else if ("installs".equals(cmd)) {
21154                dumpState.setDump(DumpState.DUMP_INSTALLS);
21155            } else if ("frozen".equals(cmd)) {
21156                dumpState.setDump(DumpState.DUMP_FROZEN);
21157            } else if ("volumes".equals(cmd)) {
21158                dumpState.setDump(DumpState.DUMP_VOLUMES);
21159            } else if ("dexopt".equals(cmd)) {
21160                dumpState.setDump(DumpState.DUMP_DEXOPT);
21161            } else if ("compiler-stats".equals(cmd)) {
21162                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21163            } else if ("changes".equals(cmd)) {
21164                dumpState.setDump(DumpState.DUMP_CHANGES);
21165            } else if ("service-permissions".equals(cmd)) {
21166                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21167            } else if ("write".equals(cmd)) {
21168                synchronized (mPackages) {
21169                    mSettings.writeLPr();
21170                    pw.println("Settings written.");
21171                    return;
21172                }
21173            }
21174        }
21175
21176        if (checkin) {
21177            pw.println("vers,1");
21178        }
21179
21180        // reader
21181        synchronized (mPackages) {
21182            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21183                if (!checkin) {
21184                    if (dumpState.onTitlePrinted())
21185                        pw.println();
21186                    pw.println("Database versions:");
21187                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21188                }
21189            }
21190
21191            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21192                if (!checkin) {
21193                    if (dumpState.onTitlePrinted())
21194                        pw.println();
21195                    pw.println("Verifiers:");
21196                    pw.print("  Required: ");
21197                    pw.print(mRequiredVerifierPackage);
21198                    pw.print(" (uid=");
21199                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21200                            UserHandle.USER_SYSTEM));
21201                    pw.println(")");
21202                } else if (mRequiredVerifierPackage != null) {
21203                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21204                    pw.print(",");
21205                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21206                            UserHandle.USER_SYSTEM));
21207                }
21208            }
21209
21210            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21211                    packageName == null) {
21212                if (mIntentFilterVerifierComponent != null) {
21213                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21214                    if (!checkin) {
21215                        if (dumpState.onTitlePrinted())
21216                            pw.println();
21217                        pw.println("Intent Filter Verifier:");
21218                        pw.print("  Using: ");
21219                        pw.print(verifierPackageName);
21220                        pw.print(" (uid=");
21221                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21222                                UserHandle.USER_SYSTEM));
21223                        pw.println(")");
21224                    } else if (verifierPackageName != null) {
21225                        pw.print("ifv,"); pw.print(verifierPackageName);
21226                        pw.print(",");
21227                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21228                                UserHandle.USER_SYSTEM));
21229                    }
21230                } else {
21231                    pw.println();
21232                    pw.println("No Intent Filter Verifier available!");
21233                }
21234            }
21235
21236            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21237                boolean printedHeader = false;
21238                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21239                while (it.hasNext()) {
21240                    String libName = it.next();
21241                    LongSparseArray<SharedLibraryEntry> versionedLib
21242                            = mSharedLibraries.get(libName);
21243                    if (versionedLib == null) {
21244                        continue;
21245                    }
21246                    final int versionCount = versionedLib.size();
21247                    for (int i = 0; i < versionCount; i++) {
21248                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21249                        if (!checkin) {
21250                            if (!printedHeader) {
21251                                if (dumpState.onTitlePrinted())
21252                                    pw.println();
21253                                pw.println("Libraries:");
21254                                printedHeader = true;
21255                            }
21256                            pw.print("  ");
21257                        } else {
21258                            pw.print("lib,");
21259                        }
21260                        pw.print(libEntry.info.getName());
21261                        if (libEntry.info.isStatic()) {
21262                            pw.print(" version=" + libEntry.info.getLongVersion());
21263                        }
21264                        if (!checkin) {
21265                            pw.print(" -> ");
21266                        }
21267                        if (libEntry.path != null) {
21268                            pw.print(" (jar) ");
21269                            pw.print(libEntry.path);
21270                        } else {
21271                            pw.print(" (apk) ");
21272                            pw.print(libEntry.apk);
21273                        }
21274                        pw.println();
21275                    }
21276                }
21277            }
21278
21279            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21280                if (dumpState.onTitlePrinted())
21281                    pw.println();
21282                if (!checkin) {
21283                    pw.println("Features:");
21284                }
21285
21286                synchronized (mAvailableFeatures) {
21287                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21288                        if (checkin) {
21289                            pw.print("feat,");
21290                            pw.print(feat.name);
21291                            pw.print(",");
21292                            pw.println(feat.version);
21293                        } else {
21294                            pw.print("  ");
21295                            pw.print(feat.name);
21296                            if (feat.version > 0) {
21297                                pw.print(" version=");
21298                                pw.print(feat.version);
21299                            }
21300                            pw.println();
21301                        }
21302                    }
21303                }
21304            }
21305
21306            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21307                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21308                        : "Activity Resolver Table:", "  ", packageName,
21309                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21310                    dumpState.setTitlePrinted(true);
21311                }
21312            }
21313            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21314                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21315                        : "Receiver Resolver Table:", "  ", packageName,
21316                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21317                    dumpState.setTitlePrinted(true);
21318                }
21319            }
21320            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21321                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21322                        : "Service Resolver Table:", "  ", packageName,
21323                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21324                    dumpState.setTitlePrinted(true);
21325                }
21326            }
21327            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21328                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21329                        : "Provider Resolver Table:", "  ", packageName,
21330                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21331                    dumpState.setTitlePrinted(true);
21332                }
21333            }
21334
21335            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21336                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21337                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21338                    int user = mSettings.mPreferredActivities.keyAt(i);
21339                    if (pir.dump(pw,
21340                            dumpState.getTitlePrinted()
21341                                ? "\nPreferred Activities User " + user + ":"
21342                                : "Preferred Activities User " + user + ":", "  ",
21343                            packageName, true, false)) {
21344                        dumpState.setTitlePrinted(true);
21345                    }
21346                }
21347            }
21348
21349            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21350                pw.flush();
21351                FileOutputStream fout = new FileOutputStream(fd);
21352                BufferedOutputStream str = new BufferedOutputStream(fout);
21353                XmlSerializer serializer = new FastXmlSerializer();
21354                try {
21355                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21356                    serializer.startDocument(null, true);
21357                    serializer.setFeature(
21358                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21359                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21360                    serializer.endDocument();
21361                    serializer.flush();
21362                } catch (IllegalArgumentException e) {
21363                    pw.println("Failed writing: " + e);
21364                } catch (IllegalStateException e) {
21365                    pw.println("Failed writing: " + e);
21366                } catch (IOException e) {
21367                    pw.println("Failed writing: " + e);
21368                }
21369            }
21370
21371            if (!checkin
21372                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21373                    && packageName == null) {
21374                pw.println();
21375                int count = mSettings.mPackages.size();
21376                if (count == 0) {
21377                    pw.println("No applications!");
21378                    pw.println();
21379                } else {
21380                    final String prefix = "  ";
21381                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21382                    if (allPackageSettings.size() == 0) {
21383                        pw.println("No domain preferred apps!");
21384                        pw.println();
21385                    } else {
21386                        pw.println("App verification status:");
21387                        pw.println();
21388                        count = 0;
21389                        for (PackageSetting ps : allPackageSettings) {
21390                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21391                            if (ivi == null || ivi.getPackageName() == null) continue;
21392                            pw.println(prefix + "Package: " + ivi.getPackageName());
21393                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21394                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21395                            pw.println();
21396                            count++;
21397                        }
21398                        if (count == 0) {
21399                            pw.println(prefix + "No app verification established.");
21400                            pw.println();
21401                        }
21402                        for (int userId : sUserManager.getUserIds()) {
21403                            pw.println("App linkages for user " + userId + ":");
21404                            pw.println();
21405                            count = 0;
21406                            for (PackageSetting ps : allPackageSettings) {
21407                                final long status = ps.getDomainVerificationStatusForUser(userId);
21408                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21409                                        && !DEBUG_DOMAIN_VERIFICATION) {
21410                                    continue;
21411                                }
21412                                pw.println(prefix + "Package: " + ps.name);
21413                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21414                                String statusStr = IntentFilterVerificationInfo.
21415                                        getStatusStringFromValue(status);
21416                                pw.println(prefix + "Status:  " + statusStr);
21417                                pw.println();
21418                                count++;
21419                            }
21420                            if (count == 0) {
21421                                pw.println(prefix + "No configured app linkages.");
21422                                pw.println();
21423                            }
21424                        }
21425                    }
21426                }
21427            }
21428
21429            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21430                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21431            }
21432
21433            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21434                boolean printedSomething = false;
21435                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21436                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21437                        continue;
21438                    }
21439                    if (!printedSomething) {
21440                        if (dumpState.onTitlePrinted())
21441                            pw.println();
21442                        pw.println("Registered ContentProviders:");
21443                        printedSomething = true;
21444                    }
21445                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21446                    pw.print("    "); pw.println(p.toString());
21447                }
21448                printedSomething = false;
21449                for (Map.Entry<String, PackageParser.Provider> entry :
21450                        mProvidersByAuthority.entrySet()) {
21451                    PackageParser.Provider p = entry.getValue();
21452                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21453                        continue;
21454                    }
21455                    if (!printedSomething) {
21456                        if (dumpState.onTitlePrinted())
21457                            pw.println();
21458                        pw.println("ContentProvider Authorities:");
21459                        printedSomething = true;
21460                    }
21461                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21462                    pw.print("    "); pw.println(p.toString());
21463                    if (p.info != null && p.info.applicationInfo != null) {
21464                        final String appInfo = p.info.applicationInfo.toString();
21465                        pw.print("      applicationInfo="); pw.println(appInfo);
21466                    }
21467                }
21468            }
21469
21470            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21471                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21472            }
21473
21474            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21475                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21476            }
21477
21478            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21479                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21480            }
21481
21482            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21483                if (dumpState.onTitlePrinted()) pw.println();
21484                pw.println("Package Changes:");
21485                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21486                final int K = mChangedPackages.size();
21487                for (int i = 0; i < K; i++) {
21488                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21489                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21490                    final int N = changes.size();
21491                    if (N == 0) {
21492                        pw.print("    "); pw.println("No packages changed");
21493                    } else {
21494                        for (int j = 0; j < N; j++) {
21495                            final String pkgName = changes.valueAt(j);
21496                            final int sequenceNumber = changes.keyAt(j);
21497                            pw.print("    ");
21498                            pw.print("seq=");
21499                            pw.print(sequenceNumber);
21500                            pw.print(", package=");
21501                            pw.println(pkgName);
21502                        }
21503                    }
21504                }
21505            }
21506
21507            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21508                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21509            }
21510
21511            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21512                // XXX should handle packageName != null by dumping only install data that
21513                // the given package is involved with.
21514                if (dumpState.onTitlePrinted()) pw.println();
21515
21516                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21517                    ipw.println();
21518                    ipw.println("Frozen packages:");
21519                    ipw.increaseIndent();
21520                    if (mFrozenPackages.size() == 0) {
21521                        ipw.println("(none)");
21522                    } else {
21523                        for (int i = 0; i < mFrozenPackages.size(); i++) {
21524                            ipw.println(mFrozenPackages.valueAt(i));
21525                        }
21526                    }
21527                    ipw.decreaseIndent();
21528                }
21529            }
21530
21531            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21532                if (dumpState.onTitlePrinted()) pw.println();
21533
21534                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21535                    ipw.println();
21536                    ipw.println("Loaded volumes:");
21537                    ipw.increaseIndent();
21538                    if (mLoadedVolumes.size() == 0) {
21539                        ipw.println("(none)");
21540                    } else {
21541                        for (int i = 0; i < mLoadedVolumes.size(); i++) {
21542                            ipw.println(mLoadedVolumes.valueAt(i));
21543                        }
21544                    }
21545                    ipw.decreaseIndent();
21546                }
21547            }
21548
21549            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21550                    && packageName == null) {
21551                if (dumpState.onTitlePrinted()) pw.println();
21552                pw.println("Service permissions:");
21553
21554                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21555                while (filterIterator.hasNext()) {
21556                    final ServiceIntentInfo info = filterIterator.next();
21557                    final ServiceInfo serviceInfo = info.service.info;
21558                    final String permission = serviceInfo.permission;
21559                    if (permission != null) {
21560                        pw.print("    ");
21561                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21562                        pw.print(": ");
21563                        pw.println(permission);
21564                    }
21565                }
21566            }
21567
21568            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21569                if (dumpState.onTitlePrinted()) pw.println();
21570                dumpDexoptStateLPr(pw, packageName);
21571            }
21572
21573            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21574                if (dumpState.onTitlePrinted()) pw.println();
21575                dumpCompilerStatsLPr(pw, packageName);
21576            }
21577
21578            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21579                if (dumpState.onTitlePrinted()) pw.println();
21580                mSettings.dumpReadMessagesLPr(pw, dumpState);
21581
21582                pw.println();
21583                pw.println("Package warning messages:");
21584                dumpCriticalInfo(pw, null);
21585            }
21586
21587            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21588                dumpCriticalInfo(pw, "msg,");
21589            }
21590        }
21591
21592        // PackageInstaller should be called outside of mPackages lock
21593        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21594            // XXX should handle packageName != null by dumping only install data that
21595            // the given package is involved with.
21596            if (dumpState.onTitlePrinted()) pw.println();
21597            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21598        }
21599    }
21600
21601    private void dumpProto(FileDescriptor fd) {
21602        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21603
21604        synchronized (mPackages) {
21605            final long requiredVerifierPackageToken =
21606                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21607            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21608            proto.write(
21609                    PackageServiceDumpProto.PackageShortProto.UID,
21610                    getPackageUid(
21611                            mRequiredVerifierPackage,
21612                            MATCH_DEBUG_TRIAGED_MISSING,
21613                            UserHandle.USER_SYSTEM));
21614            proto.end(requiredVerifierPackageToken);
21615
21616            if (mIntentFilterVerifierComponent != null) {
21617                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21618                final long verifierPackageToken =
21619                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21620                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21621                proto.write(
21622                        PackageServiceDumpProto.PackageShortProto.UID,
21623                        getPackageUid(
21624                                verifierPackageName,
21625                                MATCH_DEBUG_TRIAGED_MISSING,
21626                                UserHandle.USER_SYSTEM));
21627                proto.end(verifierPackageToken);
21628            }
21629
21630            dumpSharedLibrariesProto(proto);
21631            dumpFeaturesProto(proto);
21632            mSettings.dumpPackagesProto(proto);
21633            mSettings.dumpSharedUsersProto(proto);
21634            dumpCriticalInfo(proto);
21635        }
21636        proto.flush();
21637    }
21638
21639    private void dumpFeaturesProto(ProtoOutputStream proto) {
21640        synchronized (mAvailableFeatures) {
21641            final int count = mAvailableFeatures.size();
21642            for (int i = 0; i < count; i++) {
21643                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21644            }
21645        }
21646    }
21647
21648    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21649        final int count = mSharedLibraries.size();
21650        for (int i = 0; i < count; i++) {
21651            final String libName = mSharedLibraries.keyAt(i);
21652            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21653            if (versionedLib == null) {
21654                continue;
21655            }
21656            final int versionCount = versionedLib.size();
21657            for (int j = 0; j < versionCount; j++) {
21658                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21659                final long sharedLibraryToken =
21660                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21661                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21662                final boolean isJar = (libEntry.path != null);
21663                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21664                if (isJar) {
21665                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21666                } else {
21667                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21668                }
21669                proto.end(sharedLibraryToken);
21670            }
21671        }
21672    }
21673
21674    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21675        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21676            ipw.println();
21677            ipw.println("Dexopt state:");
21678            ipw.increaseIndent();
21679            Collection<PackageParser.Package> packages = null;
21680            if (packageName != null) {
21681                PackageParser.Package targetPackage = mPackages.get(packageName);
21682                if (targetPackage != null) {
21683                    packages = Collections.singletonList(targetPackage);
21684                } else {
21685                    ipw.println("Unable to find package: " + packageName);
21686                    return;
21687                }
21688            } else {
21689                packages = mPackages.values();
21690            }
21691
21692            for (PackageParser.Package pkg : packages) {
21693                ipw.println("[" + pkg.packageName + "]");
21694                ipw.increaseIndent();
21695                mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21696                        mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21697                ipw.decreaseIndent();
21698            }
21699        }
21700    }
21701
21702    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21703        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21704            ipw.println();
21705            ipw.println("Compiler stats:");
21706            ipw.increaseIndent();
21707            Collection<PackageParser.Package> packages = null;
21708            if (packageName != null) {
21709                PackageParser.Package targetPackage = mPackages.get(packageName);
21710                if (targetPackage != null) {
21711                    packages = Collections.singletonList(targetPackage);
21712                } else {
21713                    ipw.println("Unable to find package: " + packageName);
21714                    return;
21715                }
21716            } else {
21717                packages = mPackages.values();
21718            }
21719
21720            for (PackageParser.Package pkg : packages) {
21721                ipw.println("[" + pkg.packageName + "]");
21722                ipw.increaseIndent();
21723
21724                CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21725                if (stats == null) {
21726                    ipw.println("(No recorded stats)");
21727                } else {
21728                    stats.dump(ipw);
21729                }
21730                ipw.decreaseIndent();
21731            }
21732        }
21733    }
21734
21735    private String dumpDomainString(String packageName) {
21736        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21737                .getList();
21738        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21739
21740        ArraySet<String> result = new ArraySet<>();
21741        if (iviList.size() > 0) {
21742            for (IntentFilterVerificationInfo ivi : iviList) {
21743                for (String host : ivi.getDomains()) {
21744                    result.add(host);
21745                }
21746            }
21747        }
21748        if (filters != null && filters.size() > 0) {
21749            for (IntentFilter filter : filters) {
21750                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21751                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21752                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21753                    result.addAll(filter.getHostsList());
21754                }
21755            }
21756        }
21757
21758        StringBuilder sb = new StringBuilder(result.size() * 16);
21759        for (String domain : result) {
21760            if (sb.length() > 0) sb.append(" ");
21761            sb.append(domain);
21762        }
21763        return sb.toString();
21764    }
21765
21766    // ------- apps on sdcard specific code -------
21767    static final boolean DEBUG_SD_INSTALL = false;
21768
21769    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21770
21771    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21772
21773    private boolean mMediaMounted = false;
21774
21775    static String getEncryptKey() {
21776        try {
21777            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21778                    SD_ENCRYPTION_KEYSTORE_NAME);
21779            if (sdEncKey == null) {
21780                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21781                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21782                if (sdEncKey == null) {
21783                    Slog.e(TAG, "Failed to create encryption keys");
21784                    return null;
21785                }
21786            }
21787            return sdEncKey;
21788        } catch (NoSuchAlgorithmException nsae) {
21789            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21790            return null;
21791        } catch (IOException ioe) {
21792            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21793            return null;
21794        }
21795    }
21796
21797    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21798            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21799        final int size = infos.size();
21800        final String[] packageNames = new String[size];
21801        final int[] packageUids = new int[size];
21802        for (int i = 0; i < size; i++) {
21803            final ApplicationInfo info = infos.get(i);
21804            packageNames[i] = info.packageName;
21805            packageUids[i] = info.uid;
21806        }
21807        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21808                finishedReceiver);
21809    }
21810
21811    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21812            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21813        sendResourcesChangedBroadcast(mediaStatus, replacing,
21814                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21815    }
21816
21817    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21818            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21819        int size = pkgList.length;
21820        if (size > 0) {
21821            // Send broadcasts here
21822            Bundle extras = new Bundle();
21823            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21824            if (uidArr != null) {
21825                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21826            }
21827            if (replacing) {
21828                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21829            }
21830            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21831                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21832            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21833        }
21834    }
21835
21836    private void loadPrivatePackages(final VolumeInfo vol) {
21837        mHandler.post(new Runnable() {
21838            @Override
21839            public void run() {
21840                loadPrivatePackagesInner(vol);
21841            }
21842        });
21843    }
21844
21845    private void loadPrivatePackagesInner(VolumeInfo vol) {
21846        final String volumeUuid = vol.fsUuid;
21847        if (TextUtils.isEmpty(volumeUuid)) {
21848            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21849            return;
21850        }
21851
21852        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21853        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21854        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21855
21856        final VersionInfo ver;
21857        final List<PackageSetting> packages;
21858        synchronized (mPackages) {
21859            ver = mSettings.findOrCreateVersion(volumeUuid);
21860            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21861        }
21862
21863        for (PackageSetting ps : packages) {
21864            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21865            synchronized (mInstallLock) {
21866                final PackageParser.Package pkg;
21867                try {
21868                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21869                    loaded.add(pkg.applicationInfo);
21870
21871                } catch (PackageManagerException e) {
21872                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21873                }
21874
21875                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21876                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21877                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21878                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21879                }
21880            }
21881        }
21882
21883        // Reconcile app data for all started/unlocked users
21884        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21885        final UserManager um = mContext.getSystemService(UserManager.class);
21886        UserManagerInternal umInternal = getUserManagerInternal();
21887        for (UserInfo user : um.getUsers()) {
21888            final int flags;
21889            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21890                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21891            } else if (umInternal.isUserRunning(user.id)) {
21892                flags = StorageManager.FLAG_STORAGE_DE;
21893            } else {
21894                continue;
21895            }
21896
21897            try {
21898                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21899                synchronized (mInstallLock) {
21900                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21901                }
21902            } catch (IllegalStateException e) {
21903                // Device was probably ejected, and we'll process that event momentarily
21904                Slog.w(TAG, "Failed to prepare storage: " + e);
21905            }
21906        }
21907
21908        synchronized (mPackages) {
21909            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21910            if (sdkUpdated) {
21911                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21912                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21913            }
21914            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21915                    mPermissionCallback);
21916
21917            // Yay, everything is now upgraded
21918            ver.forceCurrent();
21919
21920            mSettings.writeLPr();
21921        }
21922
21923        for (PackageFreezer freezer : freezers) {
21924            freezer.close();
21925        }
21926
21927        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21928        sendResourcesChangedBroadcast(true, false, loaded, null);
21929        mLoadedVolumes.add(vol.getId());
21930    }
21931
21932    private void unloadPrivatePackages(final VolumeInfo vol) {
21933        mHandler.post(new Runnable() {
21934            @Override
21935            public void run() {
21936                unloadPrivatePackagesInner(vol);
21937            }
21938        });
21939    }
21940
21941    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21942        final String volumeUuid = vol.fsUuid;
21943        if (TextUtils.isEmpty(volumeUuid)) {
21944            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21945            return;
21946        }
21947
21948        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21949        synchronized (mInstallLock) {
21950        synchronized (mPackages) {
21951            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21952            for (PackageSetting ps : packages) {
21953                if (ps.pkg == null) continue;
21954
21955                final ApplicationInfo info = ps.pkg.applicationInfo;
21956                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21957                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21958
21959                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21960                        "unloadPrivatePackagesInner")) {
21961                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21962                            false, null)) {
21963                        unloaded.add(info);
21964                    } else {
21965                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21966                    }
21967                }
21968
21969                // Try very hard to release any references to this package
21970                // so we don't risk the system server being killed due to
21971                // open FDs
21972                AttributeCache.instance().removePackage(ps.name);
21973            }
21974
21975            mSettings.writeLPr();
21976        }
21977        }
21978
21979        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21980        sendResourcesChangedBroadcast(false, false, unloaded, null);
21981        mLoadedVolumes.remove(vol.getId());
21982
21983        // Try very hard to release any references to this path so we don't risk
21984        // the system server being killed due to open FDs
21985        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21986
21987        for (int i = 0; i < 3; i++) {
21988            System.gc();
21989            System.runFinalization();
21990        }
21991    }
21992
21993    private void assertPackageKnown(String volumeUuid, String packageName)
21994            throws PackageManagerException {
21995        synchronized (mPackages) {
21996            // Normalize package name to handle renamed packages
21997            packageName = normalizePackageNameLPr(packageName);
21998
21999            final PackageSetting ps = mSettings.mPackages.get(packageName);
22000            if (ps == null) {
22001                throw new PackageManagerException("Package " + packageName + " is unknown");
22002            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22003                throw new PackageManagerException(
22004                        "Package " + packageName + " found on unknown volume " + volumeUuid
22005                                + "; expected volume " + ps.volumeUuid);
22006            }
22007        }
22008    }
22009
22010    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22011            throws PackageManagerException {
22012        synchronized (mPackages) {
22013            // Normalize package name to handle renamed packages
22014            packageName = normalizePackageNameLPr(packageName);
22015
22016            final PackageSetting ps = mSettings.mPackages.get(packageName);
22017            if (ps == null) {
22018                throw new PackageManagerException("Package " + packageName + " is unknown");
22019            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22020                throw new PackageManagerException(
22021                        "Package " + packageName + " found on unknown volume " + volumeUuid
22022                                + "; expected volume " + ps.volumeUuid);
22023            } else if (!ps.getInstalled(userId)) {
22024                throw new PackageManagerException(
22025                        "Package " + packageName + " not installed for user " + userId);
22026            }
22027        }
22028    }
22029
22030    private List<String> collectAbsoluteCodePaths() {
22031        synchronized (mPackages) {
22032            List<String> codePaths = new ArrayList<>();
22033            final int packageCount = mSettings.mPackages.size();
22034            for (int i = 0; i < packageCount; i++) {
22035                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22036                codePaths.add(ps.codePath.getAbsolutePath());
22037            }
22038            return codePaths;
22039        }
22040    }
22041
22042    /**
22043     * Examine all apps present on given mounted volume, and destroy apps that
22044     * aren't expected, either due to uninstallation or reinstallation on
22045     * another volume.
22046     */
22047    private void reconcileApps(String volumeUuid) {
22048        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22049        List<File> filesToDelete = null;
22050
22051        final File[] files = FileUtils.listFilesOrEmpty(
22052                Environment.getDataAppDirectory(volumeUuid));
22053        for (File file : files) {
22054            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22055                    && !PackageInstallerService.isStageName(file.getName());
22056            if (!isPackage) {
22057                // Ignore entries which are not packages
22058                continue;
22059            }
22060
22061            String absolutePath = file.getAbsolutePath();
22062
22063            boolean pathValid = false;
22064            final int absoluteCodePathCount = absoluteCodePaths.size();
22065            for (int i = 0; i < absoluteCodePathCount; i++) {
22066                String absoluteCodePath = absoluteCodePaths.get(i);
22067                if (absolutePath.startsWith(absoluteCodePath)) {
22068                    pathValid = true;
22069                    break;
22070                }
22071            }
22072
22073            if (!pathValid) {
22074                if (filesToDelete == null) {
22075                    filesToDelete = new ArrayList<>();
22076                }
22077                filesToDelete.add(file);
22078            }
22079        }
22080
22081        if (filesToDelete != null) {
22082            final int fileToDeleteCount = filesToDelete.size();
22083            for (int i = 0; i < fileToDeleteCount; i++) {
22084                File fileToDelete = filesToDelete.get(i);
22085                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22086                synchronized (mInstallLock) {
22087                    removeCodePathLI(fileToDelete);
22088                }
22089            }
22090        }
22091    }
22092
22093    /**
22094     * Reconcile all app data for the given user.
22095     * <p>
22096     * Verifies that directories exist and that ownership and labeling is
22097     * correct for all installed apps on all mounted volumes.
22098     */
22099    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22100        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22101        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22102            final String volumeUuid = vol.getFsUuid();
22103            synchronized (mInstallLock) {
22104                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22105            }
22106        }
22107    }
22108
22109    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22110            boolean migrateAppData) {
22111        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22112    }
22113
22114    /**
22115     * Reconcile all app data on given mounted volume.
22116     * <p>
22117     * Destroys app data that isn't expected, either due to uninstallation or
22118     * reinstallation on another volume.
22119     * <p>
22120     * Verifies that directories exist and that ownership and labeling is
22121     * correct for all installed apps.
22122     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22123     */
22124    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22125            boolean migrateAppData, boolean onlyCoreApps) {
22126        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22127                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22128        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22129
22130        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22131        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22132
22133        // First look for stale data that doesn't belong, and check if things
22134        // have changed since we did our last restorecon
22135        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22136            if (StorageManager.isFileEncryptedNativeOrEmulated()
22137                    && !StorageManager.isUserKeyUnlocked(userId)) {
22138                throw new RuntimeException(
22139                        "Yikes, someone asked us to reconcile CE storage while " + userId
22140                                + " was still locked; this would have caused massive data loss!");
22141            }
22142
22143            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22144            for (File file : files) {
22145                final String packageName = file.getName();
22146                try {
22147                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22148                } catch (PackageManagerException e) {
22149                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22150                    try {
22151                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22152                                StorageManager.FLAG_STORAGE_CE, 0);
22153                    } catch (InstallerException e2) {
22154                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22155                    }
22156                }
22157            }
22158        }
22159        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22160            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22161            for (File file : files) {
22162                final String packageName = file.getName();
22163                try {
22164                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22165                } catch (PackageManagerException e) {
22166                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22167                    try {
22168                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22169                                StorageManager.FLAG_STORAGE_DE, 0);
22170                    } catch (InstallerException e2) {
22171                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22172                    }
22173                }
22174            }
22175        }
22176
22177        // Ensure that data directories are ready to roll for all packages
22178        // installed for this volume and user
22179        final List<PackageSetting> packages;
22180        synchronized (mPackages) {
22181            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22182        }
22183        int preparedCount = 0;
22184        for (PackageSetting ps : packages) {
22185            final String packageName = ps.name;
22186            if (ps.pkg == null) {
22187                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22188                // TODO: might be due to legacy ASEC apps; we should circle back
22189                // and reconcile again once they're scanned
22190                continue;
22191            }
22192            // Skip non-core apps if requested
22193            if (onlyCoreApps && !ps.pkg.coreApp) {
22194                result.add(packageName);
22195                continue;
22196            }
22197
22198            if (ps.getInstalled(userId)) {
22199                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22200                preparedCount++;
22201            }
22202        }
22203
22204        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22205        return result;
22206    }
22207
22208    /**
22209     * Prepare app data for the given app just after it was installed or
22210     * upgraded. This method carefully only touches users that it's installed
22211     * for, and it forces a restorecon to handle any seinfo changes.
22212     * <p>
22213     * Verifies that directories exist and that ownership and labeling is
22214     * correct for all installed apps. If there is an ownership mismatch, it
22215     * will try recovering system apps by wiping data; third-party app data is
22216     * left intact.
22217     * <p>
22218     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22219     */
22220    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22221        final PackageSetting ps;
22222        synchronized (mPackages) {
22223            ps = mSettings.mPackages.get(pkg.packageName);
22224            mSettings.writeKernelMappingLPr(ps);
22225        }
22226
22227        final UserManager um = mContext.getSystemService(UserManager.class);
22228        UserManagerInternal umInternal = getUserManagerInternal();
22229        for (UserInfo user : um.getUsers()) {
22230            final int flags;
22231            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22232                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22233            } else if (umInternal.isUserRunning(user.id)) {
22234                flags = StorageManager.FLAG_STORAGE_DE;
22235            } else {
22236                continue;
22237            }
22238
22239            if (ps.getInstalled(user.id)) {
22240                // TODO: when user data is locked, mark that we're still dirty
22241                prepareAppDataLIF(pkg, user.id, flags);
22242            }
22243        }
22244    }
22245
22246    /**
22247     * Prepare app data for the given app.
22248     * <p>
22249     * Verifies that directories exist and that ownership and labeling is
22250     * correct for all installed apps. If there is an ownership mismatch, this
22251     * will try recovering system apps by wiping data; third-party app data is
22252     * left intact.
22253     */
22254    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22255        if (pkg == null) {
22256            Slog.wtf(TAG, "Package was null!", new Throwable());
22257            return;
22258        }
22259        prepareAppDataLeafLIF(pkg, userId, flags);
22260        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22261        for (int i = 0; i < childCount; i++) {
22262            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22263        }
22264    }
22265
22266    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22267            boolean maybeMigrateAppData) {
22268        prepareAppDataLIF(pkg, userId, flags);
22269
22270        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22271            // We may have just shuffled around app data directories, so
22272            // prepare them one more time
22273            prepareAppDataLIF(pkg, userId, flags);
22274        }
22275    }
22276
22277    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22278        if (DEBUG_APP_DATA) {
22279            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22280                    + Integer.toHexString(flags));
22281        }
22282
22283        final String volumeUuid = pkg.volumeUuid;
22284        final String packageName = pkg.packageName;
22285        final ApplicationInfo app = pkg.applicationInfo;
22286        final int appId = UserHandle.getAppId(app.uid);
22287
22288        Preconditions.checkNotNull(app.seInfo);
22289
22290        long ceDataInode = -1;
22291        try {
22292            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22293                    appId, app.seInfo, app.targetSdkVersion);
22294        } catch (InstallerException e) {
22295            if (app.isSystemApp()) {
22296                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22297                        + ", but trying to recover: " + e);
22298                destroyAppDataLeafLIF(pkg, userId, flags);
22299                try {
22300                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22301                            appId, app.seInfo, app.targetSdkVersion);
22302                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22303                } catch (InstallerException e2) {
22304                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22305                }
22306            } else {
22307                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22308            }
22309        }
22310        // Prepare the application profiles only for upgrades and first boot (so that we don't
22311        // repeat the same operation at each boot).
22312        // We only have to cover the upgrade and first boot here because for app installs we
22313        // prepare the profiles before invoking dexopt (in installPackageLI).
22314        //
22315        // We also have to cover non system users because we do not call the usual install package
22316        // methods for them.
22317        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22318            mArtManagerService.prepareAppProfiles(pkg, userId);
22319        }
22320
22321        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22322            // TODO: mark this structure as dirty so we persist it!
22323            synchronized (mPackages) {
22324                final PackageSetting ps = mSettings.mPackages.get(packageName);
22325                if (ps != null) {
22326                    ps.setCeDataInode(ceDataInode, userId);
22327                }
22328            }
22329        }
22330
22331        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22332    }
22333
22334    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22335        if (pkg == null) {
22336            Slog.wtf(TAG, "Package was null!", new Throwable());
22337            return;
22338        }
22339        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22340        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22341        for (int i = 0; i < childCount; i++) {
22342            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22343        }
22344    }
22345
22346    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22347        final String volumeUuid = pkg.volumeUuid;
22348        final String packageName = pkg.packageName;
22349        final ApplicationInfo app = pkg.applicationInfo;
22350
22351        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22352            // Create a native library symlink only if we have native libraries
22353            // and if the native libraries are 32 bit libraries. We do not provide
22354            // this symlink for 64 bit libraries.
22355            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22356                final String nativeLibPath = app.nativeLibraryDir;
22357                try {
22358                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22359                            nativeLibPath, userId);
22360                } catch (InstallerException e) {
22361                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22362                }
22363            }
22364        }
22365    }
22366
22367    /**
22368     * For system apps on non-FBE devices, this method migrates any existing
22369     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22370     * requested by the app.
22371     */
22372    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22373        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22374                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22375            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22376                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22377            try {
22378                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22379                        storageTarget);
22380            } catch (InstallerException e) {
22381                logCriticalInfo(Log.WARN,
22382                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22383            }
22384            return true;
22385        } else {
22386            return false;
22387        }
22388    }
22389
22390    public PackageFreezer freezePackage(String packageName, String killReason) {
22391        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22392    }
22393
22394    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22395        return new PackageFreezer(packageName, userId, killReason);
22396    }
22397
22398    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22399            String killReason) {
22400        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22401    }
22402
22403    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22404            String killReason) {
22405        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22406            return new PackageFreezer();
22407        } else {
22408            return freezePackage(packageName, userId, killReason);
22409        }
22410    }
22411
22412    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22413            String killReason) {
22414        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22415    }
22416
22417    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22418            String killReason) {
22419        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22420            return new PackageFreezer();
22421        } else {
22422            return freezePackage(packageName, userId, killReason);
22423        }
22424    }
22425
22426    /**
22427     * Class that freezes and kills the given package upon creation, and
22428     * unfreezes it upon closing. This is typically used when doing surgery on
22429     * app code/data to prevent the app from running while you're working.
22430     */
22431    private class PackageFreezer implements AutoCloseable {
22432        private final String mPackageName;
22433        private final PackageFreezer[] mChildren;
22434
22435        private final boolean mWeFroze;
22436
22437        private final AtomicBoolean mClosed = new AtomicBoolean();
22438        private final CloseGuard mCloseGuard = CloseGuard.get();
22439
22440        /**
22441         * Create and return a stub freezer that doesn't actually do anything,
22442         * typically used when someone requested
22443         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22444         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22445         */
22446        public PackageFreezer() {
22447            mPackageName = null;
22448            mChildren = null;
22449            mWeFroze = false;
22450            mCloseGuard.open("close");
22451        }
22452
22453        public PackageFreezer(String packageName, int userId, String killReason) {
22454            synchronized (mPackages) {
22455                mPackageName = packageName;
22456                mWeFroze = mFrozenPackages.add(mPackageName);
22457
22458                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22459                if (ps != null) {
22460                    killApplication(ps.name, ps.appId, userId, killReason);
22461                }
22462
22463                final PackageParser.Package p = mPackages.get(packageName);
22464                if (p != null && p.childPackages != null) {
22465                    final int N = p.childPackages.size();
22466                    mChildren = new PackageFreezer[N];
22467                    for (int i = 0; i < N; i++) {
22468                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22469                                userId, killReason);
22470                    }
22471                } else {
22472                    mChildren = null;
22473                }
22474            }
22475            mCloseGuard.open("close");
22476        }
22477
22478        @Override
22479        protected void finalize() throws Throwable {
22480            try {
22481                if (mCloseGuard != null) {
22482                    mCloseGuard.warnIfOpen();
22483                }
22484
22485                close();
22486            } finally {
22487                super.finalize();
22488            }
22489        }
22490
22491        @Override
22492        public void close() {
22493            mCloseGuard.close();
22494            if (mClosed.compareAndSet(false, true)) {
22495                synchronized (mPackages) {
22496                    if (mWeFroze) {
22497                        mFrozenPackages.remove(mPackageName);
22498                    }
22499
22500                    if (mChildren != null) {
22501                        for (PackageFreezer freezer : mChildren) {
22502                            freezer.close();
22503                        }
22504                    }
22505                }
22506            }
22507        }
22508    }
22509
22510    /**
22511     * Verify that given package is currently frozen.
22512     */
22513    private void checkPackageFrozen(String packageName) {
22514        synchronized (mPackages) {
22515            if (!mFrozenPackages.contains(packageName)) {
22516                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22517            }
22518        }
22519    }
22520
22521    @Override
22522    public int movePackage(final String packageName, final String volumeUuid) {
22523        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22524
22525        final int callingUid = Binder.getCallingUid();
22526        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22527        final int moveId = mNextMoveId.getAndIncrement();
22528        mHandler.post(new Runnable() {
22529            @Override
22530            public void run() {
22531                try {
22532                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22533                } catch (PackageManagerException e) {
22534                    Slog.w(TAG, "Failed to move " + packageName, e);
22535                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22536                }
22537            }
22538        });
22539        return moveId;
22540    }
22541
22542    private void movePackageInternal(final String packageName, final String volumeUuid,
22543            final int moveId, final int callingUid, UserHandle user)
22544                    throws PackageManagerException {
22545        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22546        final PackageManager pm = mContext.getPackageManager();
22547
22548        final boolean currentAsec;
22549        final String currentVolumeUuid;
22550        final File codeFile;
22551        final String installerPackageName;
22552        final String packageAbiOverride;
22553        final int appId;
22554        final String seinfo;
22555        final String label;
22556        final int targetSdkVersion;
22557        final PackageFreezer freezer;
22558        final int[] installedUserIds;
22559
22560        // reader
22561        synchronized (mPackages) {
22562            final PackageParser.Package pkg = mPackages.get(packageName);
22563            final PackageSetting ps = mSettings.mPackages.get(packageName);
22564            if (pkg == null
22565                    || ps == null
22566                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22567                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22568            }
22569            if (pkg.applicationInfo.isSystemApp()) {
22570                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22571                        "Cannot move system application");
22572            }
22573
22574            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22575            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22576                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22577            if (isInternalStorage && !allow3rdPartyOnInternal) {
22578                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22579                        "3rd party apps are not allowed on internal storage");
22580            }
22581
22582            if (pkg.applicationInfo.isExternalAsec()) {
22583                currentAsec = true;
22584                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22585            } else if (pkg.applicationInfo.isForwardLocked()) {
22586                currentAsec = true;
22587                currentVolumeUuid = "forward_locked";
22588            } else {
22589                currentAsec = false;
22590                currentVolumeUuid = ps.volumeUuid;
22591
22592                final File probe = new File(pkg.codePath);
22593                final File probeOat = new File(probe, "oat");
22594                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22595                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22596                            "Move only supported for modern cluster style installs");
22597                }
22598            }
22599
22600            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22601                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22602                        "Package already moved to " + volumeUuid);
22603            }
22604            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22605                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22606                        "Device admin cannot be moved");
22607            }
22608
22609            if (mFrozenPackages.contains(packageName)) {
22610                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22611                        "Failed to move already frozen package");
22612            }
22613
22614            codeFile = new File(pkg.codePath);
22615            installerPackageName = ps.installerPackageName;
22616            packageAbiOverride = ps.cpuAbiOverrideString;
22617            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22618            seinfo = pkg.applicationInfo.seInfo;
22619            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22620            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22621            freezer = freezePackage(packageName, "movePackageInternal");
22622            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22623        }
22624
22625        final Bundle extras = new Bundle();
22626        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22627        extras.putString(Intent.EXTRA_TITLE, label);
22628        mMoveCallbacks.notifyCreated(moveId, extras);
22629
22630        int installFlags;
22631        final boolean moveCompleteApp;
22632        final File measurePath;
22633
22634        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22635            installFlags = INSTALL_INTERNAL;
22636            moveCompleteApp = !currentAsec;
22637            measurePath = Environment.getDataAppDirectory(volumeUuid);
22638        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22639            installFlags = INSTALL_EXTERNAL;
22640            moveCompleteApp = false;
22641            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22642        } else {
22643            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22644            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22645                    || !volume.isMountedWritable()) {
22646                freezer.close();
22647                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22648                        "Move location not mounted private volume");
22649            }
22650
22651            Preconditions.checkState(!currentAsec);
22652
22653            installFlags = INSTALL_INTERNAL;
22654            moveCompleteApp = true;
22655            measurePath = Environment.getDataAppDirectory(volumeUuid);
22656        }
22657
22658        // If we're moving app data around, we need all the users unlocked
22659        if (moveCompleteApp) {
22660            for (int userId : installedUserIds) {
22661                if (StorageManager.isFileEncryptedNativeOrEmulated()
22662                        && !StorageManager.isUserKeyUnlocked(userId)) {
22663                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22664                            "User " + userId + " must be unlocked");
22665                }
22666            }
22667        }
22668
22669        final PackageStats stats = new PackageStats(null, -1);
22670        synchronized (mInstaller) {
22671            for (int userId : installedUserIds) {
22672                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22673                    freezer.close();
22674                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22675                            "Failed to measure package size");
22676                }
22677            }
22678        }
22679
22680        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22681                + stats.dataSize);
22682
22683        final long startFreeBytes = measurePath.getUsableSpace();
22684        final long sizeBytes;
22685        if (moveCompleteApp) {
22686            sizeBytes = stats.codeSize + stats.dataSize;
22687        } else {
22688            sizeBytes = stats.codeSize;
22689        }
22690
22691        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22692            freezer.close();
22693            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22694                    "Not enough free space to move");
22695        }
22696
22697        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22698
22699        final CountDownLatch installedLatch = new CountDownLatch(1);
22700        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22701            @Override
22702            public void onUserActionRequired(Intent intent) throws RemoteException {
22703                throw new IllegalStateException();
22704            }
22705
22706            @Override
22707            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22708                    Bundle extras) throws RemoteException {
22709                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22710                        + PackageManager.installStatusToString(returnCode, msg));
22711
22712                installedLatch.countDown();
22713                freezer.close();
22714
22715                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22716                switch (status) {
22717                    case PackageInstaller.STATUS_SUCCESS:
22718                        mMoveCallbacks.notifyStatusChanged(moveId,
22719                                PackageManager.MOVE_SUCCEEDED);
22720                        break;
22721                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22722                        mMoveCallbacks.notifyStatusChanged(moveId,
22723                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22724                        break;
22725                    default:
22726                        mMoveCallbacks.notifyStatusChanged(moveId,
22727                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22728                        break;
22729                }
22730            }
22731        };
22732
22733        final MoveInfo move;
22734        if (moveCompleteApp) {
22735            // Kick off a thread to report progress estimates
22736            new Thread() {
22737                @Override
22738                public void run() {
22739                    while (true) {
22740                        try {
22741                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22742                                break;
22743                            }
22744                        } catch (InterruptedException ignored) {
22745                        }
22746
22747                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22748                        final int progress = 10 + (int) MathUtils.constrain(
22749                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22750                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22751                    }
22752                }
22753            }.start();
22754
22755            final String dataAppName = codeFile.getName();
22756            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22757                    dataAppName, appId, seinfo, targetSdkVersion);
22758        } else {
22759            move = null;
22760        }
22761
22762        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22763
22764        final Message msg = mHandler.obtainMessage(INIT_COPY);
22765        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22766        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22767                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22768                packageAbiOverride, null /*grantedPermissions*/,
22769                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22770        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22771        msg.obj = params;
22772
22773        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22774                System.identityHashCode(msg.obj));
22775        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22776                System.identityHashCode(msg.obj));
22777
22778        mHandler.sendMessage(msg);
22779    }
22780
22781    @Override
22782    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22783        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22784
22785        final int realMoveId = mNextMoveId.getAndIncrement();
22786        final Bundle extras = new Bundle();
22787        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22788        mMoveCallbacks.notifyCreated(realMoveId, extras);
22789
22790        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22791            @Override
22792            public void onCreated(int moveId, Bundle extras) {
22793                // Ignored
22794            }
22795
22796            @Override
22797            public void onStatusChanged(int moveId, int status, long estMillis) {
22798                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22799            }
22800        };
22801
22802        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22803        storage.setPrimaryStorageUuid(volumeUuid, callback);
22804        return realMoveId;
22805    }
22806
22807    @Override
22808    public int getMoveStatus(int moveId) {
22809        mContext.enforceCallingOrSelfPermission(
22810                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22811        return mMoveCallbacks.mLastStatus.get(moveId);
22812    }
22813
22814    @Override
22815    public void registerMoveCallback(IPackageMoveObserver callback) {
22816        mContext.enforceCallingOrSelfPermission(
22817                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22818        mMoveCallbacks.register(callback);
22819    }
22820
22821    @Override
22822    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22823        mContext.enforceCallingOrSelfPermission(
22824                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22825        mMoveCallbacks.unregister(callback);
22826    }
22827
22828    @Override
22829    public boolean setInstallLocation(int loc) {
22830        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22831                null);
22832        if (getInstallLocation() == loc) {
22833            return true;
22834        }
22835        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22836                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22837            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22838                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22839            return true;
22840        }
22841        return false;
22842   }
22843
22844    @Override
22845    public int getInstallLocation() {
22846        // allow instant app access
22847        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22848                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22849                PackageHelper.APP_INSTALL_AUTO);
22850    }
22851
22852    /** Called by UserManagerService */
22853    void cleanUpUser(UserManagerService userManager, int userHandle) {
22854        synchronized (mPackages) {
22855            mDirtyUsers.remove(userHandle);
22856            mUserNeedsBadging.delete(userHandle);
22857            mSettings.removeUserLPw(userHandle);
22858            mPendingBroadcasts.remove(userHandle);
22859            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22860            removeUnusedPackagesLPw(userManager, userHandle);
22861        }
22862    }
22863
22864    /**
22865     * We're removing userHandle and would like to remove any downloaded packages
22866     * that are no longer in use by any other user.
22867     * @param userHandle the user being removed
22868     */
22869    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22870        final boolean DEBUG_CLEAN_APKS = false;
22871        int [] users = userManager.getUserIds();
22872        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22873        while (psit.hasNext()) {
22874            PackageSetting ps = psit.next();
22875            if (ps.pkg == null) {
22876                continue;
22877            }
22878            final String packageName = ps.pkg.packageName;
22879            // Skip over if system app
22880            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22881                continue;
22882            }
22883            if (DEBUG_CLEAN_APKS) {
22884                Slog.i(TAG, "Checking package " + packageName);
22885            }
22886            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22887            if (keep) {
22888                if (DEBUG_CLEAN_APKS) {
22889                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22890                }
22891            } else {
22892                for (int i = 0; i < users.length; i++) {
22893                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22894                        keep = true;
22895                        if (DEBUG_CLEAN_APKS) {
22896                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22897                                    + users[i]);
22898                        }
22899                        break;
22900                    }
22901                }
22902            }
22903            if (!keep) {
22904                if (DEBUG_CLEAN_APKS) {
22905                    Slog.i(TAG, "  Removing package " + packageName);
22906                }
22907                mHandler.post(new Runnable() {
22908                    public void run() {
22909                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22910                                userHandle, 0);
22911                    } //end run
22912                });
22913            }
22914        }
22915    }
22916
22917    /** Called by UserManagerService */
22918    void createNewUser(int userId, String[] disallowedPackages) {
22919        synchronized (mInstallLock) {
22920            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22921        }
22922        synchronized (mPackages) {
22923            scheduleWritePackageRestrictionsLocked(userId);
22924            scheduleWritePackageListLocked(userId);
22925            applyFactoryDefaultBrowserLPw(userId);
22926            primeDomainVerificationsLPw(userId);
22927        }
22928    }
22929
22930    void onNewUserCreated(final int userId) {
22931        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22932        synchronized(mPackages) {
22933            // If permission review for legacy apps is required, we represent
22934            // dagerous permissions for such apps as always granted runtime
22935            // permissions to keep per user flag state whether review is needed.
22936            // Hence, if a new user is added we have to propagate dangerous
22937            // permission grants for these legacy apps.
22938            if (mSettings.mPermissions.mPermissionReviewRequired) {
22939// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22940                mPermissionManager.updateAllPermissions(
22941                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22942                        mPermissionCallback);
22943            }
22944        }
22945    }
22946
22947    @Override
22948    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22949        mContext.enforceCallingOrSelfPermission(
22950                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22951                "Only package verification agents can read the verifier device identity");
22952
22953        synchronized (mPackages) {
22954            return mSettings.getVerifierDeviceIdentityLPw();
22955        }
22956    }
22957
22958    @Override
22959    public void setPermissionEnforced(String permission, boolean enforced) {
22960        // TODO: Now that we no longer change GID for storage, this should to away.
22961        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22962                "setPermissionEnforced");
22963        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22964            synchronized (mPackages) {
22965                if (mSettings.mReadExternalStorageEnforced == null
22966                        || mSettings.mReadExternalStorageEnforced != enforced) {
22967                    mSettings.mReadExternalStorageEnforced =
22968                            enforced ? Boolean.TRUE : Boolean.FALSE;
22969                    mSettings.writeLPr();
22970                }
22971            }
22972            // kill any non-foreground processes so we restart them and
22973            // grant/revoke the GID.
22974            final IActivityManager am = ActivityManager.getService();
22975            if (am != null) {
22976                final long token = Binder.clearCallingIdentity();
22977                try {
22978                    am.killProcessesBelowForeground("setPermissionEnforcement");
22979                } catch (RemoteException e) {
22980                } finally {
22981                    Binder.restoreCallingIdentity(token);
22982                }
22983            }
22984        } else {
22985            throw new IllegalArgumentException("No selective enforcement for " + permission);
22986        }
22987    }
22988
22989    @Override
22990    @Deprecated
22991    public boolean isPermissionEnforced(String permission) {
22992        // allow instant applications
22993        return true;
22994    }
22995
22996    @Override
22997    public boolean isStorageLow() {
22998        // allow instant applications
22999        final long token = Binder.clearCallingIdentity();
23000        try {
23001            final DeviceStorageMonitorInternal
23002                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23003            if (dsm != null) {
23004                return dsm.isMemoryLow();
23005            } else {
23006                return false;
23007            }
23008        } finally {
23009            Binder.restoreCallingIdentity(token);
23010        }
23011    }
23012
23013    @Override
23014    public IPackageInstaller getPackageInstaller() {
23015        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23016            return null;
23017        }
23018        return mInstallerService;
23019    }
23020
23021    @Override
23022    public IArtManager getArtManager() {
23023        return mArtManagerService;
23024    }
23025
23026    private boolean userNeedsBadging(int userId) {
23027        int index = mUserNeedsBadging.indexOfKey(userId);
23028        if (index < 0) {
23029            final UserInfo userInfo;
23030            final long token = Binder.clearCallingIdentity();
23031            try {
23032                userInfo = sUserManager.getUserInfo(userId);
23033            } finally {
23034                Binder.restoreCallingIdentity(token);
23035            }
23036            final boolean b;
23037            if (userInfo != null && userInfo.isManagedProfile()) {
23038                b = true;
23039            } else {
23040                b = false;
23041            }
23042            mUserNeedsBadging.put(userId, b);
23043            return b;
23044        }
23045        return mUserNeedsBadging.valueAt(index);
23046    }
23047
23048    @Override
23049    public KeySet getKeySetByAlias(String packageName, String alias) {
23050        if (packageName == null || alias == null) {
23051            return null;
23052        }
23053        synchronized(mPackages) {
23054            final PackageParser.Package pkg = mPackages.get(packageName);
23055            if (pkg == null) {
23056                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23057                throw new IllegalArgumentException("Unknown package: " + packageName);
23058            }
23059            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23060            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23061                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23062                throw new IllegalArgumentException("Unknown package: " + packageName);
23063            }
23064            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23065            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23066        }
23067    }
23068
23069    @Override
23070    public KeySet getSigningKeySet(String packageName) {
23071        if (packageName == null) {
23072            return null;
23073        }
23074        synchronized(mPackages) {
23075            final int callingUid = Binder.getCallingUid();
23076            final int callingUserId = UserHandle.getUserId(callingUid);
23077            final PackageParser.Package pkg = mPackages.get(packageName);
23078            if (pkg == null) {
23079                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23080                throw new IllegalArgumentException("Unknown package: " + packageName);
23081            }
23082            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23083            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23084                // filter and pretend the package doesn't exist
23085                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23086                        + ", uid:" + callingUid);
23087                throw new IllegalArgumentException("Unknown package: " + packageName);
23088            }
23089            if (pkg.applicationInfo.uid != callingUid
23090                    && Process.SYSTEM_UID != callingUid) {
23091                throw new SecurityException("May not access signing KeySet of other apps.");
23092            }
23093            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23094            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23095        }
23096    }
23097
23098    @Override
23099    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23100        final int callingUid = Binder.getCallingUid();
23101        if (getInstantAppPackageName(callingUid) != null) {
23102            return false;
23103        }
23104        if (packageName == null || ks == null) {
23105            return false;
23106        }
23107        synchronized(mPackages) {
23108            final PackageParser.Package pkg = mPackages.get(packageName);
23109            if (pkg == null
23110                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23111                            UserHandle.getUserId(callingUid))) {
23112                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23113                throw new IllegalArgumentException("Unknown package: " + packageName);
23114            }
23115            IBinder ksh = ks.getToken();
23116            if (ksh instanceof KeySetHandle) {
23117                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23118                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23119            }
23120            return false;
23121        }
23122    }
23123
23124    @Override
23125    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23126        final int callingUid = Binder.getCallingUid();
23127        if (getInstantAppPackageName(callingUid) != null) {
23128            return false;
23129        }
23130        if (packageName == null || ks == null) {
23131            return false;
23132        }
23133        synchronized(mPackages) {
23134            final PackageParser.Package pkg = mPackages.get(packageName);
23135            if (pkg == null
23136                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23137                            UserHandle.getUserId(callingUid))) {
23138                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23139                throw new IllegalArgumentException("Unknown package: " + packageName);
23140            }
23141            IBinder ksh = ks.getToken();
23142            if (ksh instanceof KeySetHandle) {
23143                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23144                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23145            }
23146            return false;
23147        }
23148    }
23149
23150    private void deletePackageIfUnusedLPr(final String packageName) {
23151        PackageSetting ps = mSettings.mPackages.get(packageName);
23152        if (ps == null) {
23153            return;
23154        }
23155        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23156            // TODO Implement atomic delete if package is unused
23157            // It is currently possible that the package will be deleted even if it is installed
23158            // after this method returns.
23159            mHandler.post(new Runnable() {
23160                public void run() {
23161                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23162                            0, PackageManager.DELETE_ALL_USERS);
23163                }
23164            });
23165        }
23166    }
23167
23168    /**
23169     * Check and throw if the given before/after packages would be considered a
23170     * downgrade.
23171     */
23172    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23173            throws PackageManagerException {
23174        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23175            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23176                    "Update version code " + after.versionCode + " is older than current "
23177                    + before.getLongVersionCode());
23178        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23179            if (after.baseRevisionCode < before.baseRevisionCode) {
23180                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23181                        "Update base revision code " + after.baseRevisionCode
23182                        + " is older than current " + before.baseRevisionCode);
23183            }
23184
23185            if (!ArrayUtils.isEmpty(after.splitNames)) {
23186                for (int i = 0; i < after.splitNames.length; i++) {
23187                    final String splitName = after.splitNames[i];
23188                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23189                    if (j != -1) {
23190                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23191                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23192                                    "Update split " + splitName + " revision code "
23193                                    + after.splitRevisionCodes[i] + " is older than current "
23194                                    + before.splitRevisionCodes[j]);
23195                        }
23196                    }
23197                }
23198            }
23199        }
23200    }
23201
23202    private static class MoveCallbacks extends Handler {
23203        private static final int MSG_CREATED = 1;
23204        private static final int MSG_STATUS_CHANGED = 2;
23205
23206        private final RemoteCallbackList<IPackageMoveObserver>
23207                mCallbacks = new RemoteCallbackList<>();
23208
23209        private final SparseIntArray mLastStatus = new SparseIntArray();
23210
23211        public MoveCallbacks(Looper looper) {
23212            super(looper);
23213        }
23214
23215        public void register(IPackageMoveObserver callback) {
23216            mCallbacks.register(callback);
23217        }
23218
23219        public void unregister(IPackageMoveObserver callback) {
23220            mCallbacks.unregister(callback);
23221        }
23222
23223        @Override
23224        public void handleMessage(Message msg) {
23225            final SomeArgs args = (SomeArgs) msg.obj;
23226            final int n = mCallbacks.beginBroadcast();
23227            for (int i = 0; i < n; i++) {
23228                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23229                try {
23230                    invokeCallback(callback, msg.what, args);
23231                } catch (RemoteException ignored) {
23232                }
23233            }
23234            mCallbacks.finishBroadcast();
23235            args.recycle();
23236        }
23237
23238        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23239                throws RemoteException {
23240            switch (what) {
23241                case MSG_CREATED: {
23242                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23243                    break;
23244                }
23245                case MSG_STATUS_CHANGED: {
23246                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23247                    break;
23248                }
23249            }
23250        }
23251
23252        private void notifyCreated(int moveId, Bundle extras) {
23253            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23254
23255            final SomeArgs args = SomeArgs.obtain();
23256            args.argi1 = moveId;
23257            args.arg2 = extras;
23258            obtainMessage(MSG_CREATED, args).sendToTarget();
23259        }
23260
23261        private void notifyStatusChanged(int moveId, int status) {
23262            notifyStatusChanged(moveId, status, -1);
23263        }
23264
23265        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23266            Slog.v(TAG, "Move " + moveId + " status " + status);
23267
23268            final SomeArgs args = SomeArgs.obtain();
23269            args.argi1 = moveId;
23270            args.argi2 = status;
23271            args.arg3 = estMillis;
23272            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23273
23274            synchronized (mLastStatus) {
23275                mLastStatus.put(moveId, status);
23276            }
23277        }
23278    }
23279
23280    private final static class OnPermissionChangeListeners extends Handler {
23281        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23282
23283        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23284                new RemoteCallbackList<>();
23285
23286        public OnPermissionChangeListeners(Looper looper) {
23287            super(looper);
23288        }
23289
23290        @Override
23291        public void handleMessage(Message msg) {
23292            switch (msg.what) {
23293                case MSG_ON_PERMISSIONS_CHANGED: {
23294                    final int uid = msg.arg1;
23295                    handleOnPermissionsChanged(uid);
23296                } break;
23297            }
23298        }
23299
23300        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23301            mPermissionListeners.register(listener);
23302
23303        }
23304
23305        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23306            mPermissionListeners.unregister(listener);
23307        }
23308
23309        public void onPermissionsChanged(int uid) {
23310            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23311                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23312            }
23313        }
23314
23315        private void handleOnPermissionsChanged(int uid) {
23316            final int count = mPermissionListeners.beginBroadcast();
23317            try {
23318                for (int i = 0; i < count; i++) {
23319                    IOnPermissionsChangeListener callback = mPermissionListeners
23320                            .getBroadcastItem(i);
23321                    try {
23322                        callback.onPermissionsChanged(uid);
23323                    } catch (RemoteException e) {
23324                        Log.e(TAG, "Permission listener is dead", e);
23325                    }
23326                }
23327            } finally {
23328                mPermissionListeners.finishBroadcast();
23329            }
23330        }
23331    }
23332
23333    private class PackageManagerNative extends IPackageManagerNative.Stub {
23334        @Override
23335        public String[] getNamesForUids(int[] uids) throws RemoteException {
23336            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23337            // massage results so they can be parsed by the native binder
23338            for (int i = results.length - 1; i >= 0; --i) {
23339                if (results[i] == null) {
23340                    results[i] = "";
23341                }
23342            }
23343            return results;
23344        }
23345
23346        // NB: this differentiates between preloads and sideloads
23347        @Override
23348        public String getInstallerForPackage(String packageName) throws RemoteException {
23349            final String installerName = getInstallerPackageName(packageName);
23350            if (!TextUtils.isEmpty(installerName)) {
23351                return installerName;
23352            }
23353            // differentiate between preload and sideload
23354            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23355            ApplicationInfo appInfo = getApplicationInfo(packageName,
23356                                    /*flags*/ 0,
23357                                    /*userId*/ callingUser);
23358            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23359                return "preload";
23360            }
23361            return "";
23362        }
23363
23364        @Override
23365        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23366            try {
23367                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23368                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23369                if (pInfo != null) {
23370                    return pInfo.getLongVersionCode();
23371                }
23372            } catch (Exception e) {
23373            }
23374            return 0;
23375        }
23376    }
23377
23378    private class PackageManagerInternalImpl extends PackageManagerInternal {
23379        @Override
23380        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23381                int flagValues, int userId) {
23382            PackageManagerService.this.updatePermissionFlags(
23383                    permName, packageName, flagMask, flagValues, userId);
23384        }
23385
23386        @Override
23387        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23388            SigningDetails sd = getSigningDetails(packageName);
23389            if (sd == null) {
23390                return false;
23391            }
23392            return sd.hasSha256Certificate(restoringFromSigHash,
23393                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23394        }
23395
23396        @Override
23397        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23398            SigningDetails sd = getSigningDetails(packageName);
23399            if (sd == null) {
23400                return false;
23401            }
23402            return sd.hasCertificate(restoringFromSig,
23403                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23404        }
23405
23406        private SigningDetails getSigningDetails(@NonNull String packageName) {
23407            synchronized (mPackages) {
23408                PackageParser.Package p = mPackages.get(packageName);
23409                if (p == null) {
23410                    return null;
23411                }
23412                return p.mSigningDetails;
23413            }
23414        }
23415
23416        @Override
23417        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23418            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23419        }
23420
23421        @Override
23422        public boolean isInstantApp(String packageName, int userId) {
23423            return PackageManagerService.this.isInstantApp(packageName, userId);
23424        }
23425
23426        @Override
23427        public String getInstantAppPackageName(int uid) {
23428            return PackageManagerService.this.getInstantAppPackageName(uid);
23429        }
23430
23431        @Override
23432        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23433            synchronized (mPackages) {
23434                return PackageManagerService.this.filterAppAccessLPr(
23435                        (PackageSetting) pkg.mExtras, callingUid, userId);
23436            }
23437        }
23438
23439        @Override
23440        public PackageParser.Package getPackage(String packageName) {
23441            synchronized (mPackages) {
23442                packageName = resolveInternalPackageNameLPr(
23443                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23444                return mPackages.get(packageName);
23445            }
23446        }
23447
23448        @Override
23449        public PackageList getPackageList(PackageListObserver observer) {
23450            synchronized (mPackages) {
23451                final int N = mPackages.size();
23452                final ArrayList<String> list = new ArrayList<>(N);
23453                for (int i = 0; i < N; i++) {
23454                    list.add(mPackages.keyAt(i));
23455                }
23456                final PackageList packageList = new PackageList(list, observer);
23457                if (observer != null) {
23458                    mPackageListObservers.add(packageList);
23459                }
23460                return packageList;
23461            }
23462        }
23463
23464        @Override
23465        public void removePackageListObserver(PackageListObserver observer) {
23466            synchronized (mPackages) {
23467                mPackageListObservers.remove(observer);
23468            }
23469        }
23470
23471        @Override
23472        public PackageParser.Package getDisabledPackage(String packageName) {
23473            synchronized (mPackages) {
23474                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23475                return (ps != null) ? ps.pkg : null;
23476            }
23477        }
23478
23479        @Override
23480        public String getKnownPackageName(int knownPackage, int userId) {
23481            switch(knownPackage) {
23482                case PackageManagerInternal.PACKAGE_BROWSER:
23483                    return getDefaultBrowserPackageName(userId);
23484                case PackageManagerInternal.PACKAGE_INSTALLER:
23485                    return mRequiredInstallerPackage;
23486                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23487                    return mSetupWizardPackage;
23488                case PackageManagerInternal.PACKAGE_SYSTEM:
23489                    return "android";
23490                case PackageManagerInternal.PACKAGE_VERIFIER:
23491                    return mRequiredVerifierPackage;
23492                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23493                    return mSystemTextClassifierPackage;
23494            }
23495            return null;
23496        }
23497
23498        @Override
23499        public boolean isResolveActivityComponent(ComponentInfo component) {
23500            return mResolveActivity.packageName.equals(component.packageName)
23501                    && mResolveActivity.name.equals(component.name);
23502        }
23503
23504        @Override
23505        public void setLocationPackagesProvider(PackagesProvider provider) {
23506            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23507        }
23508
23509        @Override
23510        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23511            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23512        }
23513
23514        @Override
23515        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23516            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23517        }
23518
23519        @Override
23520        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23521            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23522        }
23523
23524        @Override
23525        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23526            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23527        }
23528
23529        @Override
23530        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23531            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23532        }
23533
23534        @Override
23535        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23536            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23537        }
23538
23539        @Override
23540        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23541            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23542        }
23543
23544        @Override
23545        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23546            synchronized (mPackages) {
23547                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23548            }
23549            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23550        }
23551
23552        @Override
23553        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23554            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23555                    packageName, userId);
23556        }
23557
23558        @Override
23559        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23560            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23561                    packageName, userId);
23562        }
23563
23564        @Override
23565        public void setKeepUninstalledPackages(final List<String> packageList) {
23566            Preconditions.checkNotNull(packageList);
23567            List<String> removedFromList = null;
23568            synchronized (mPackages) {
23569                if (mKeepUninstalledPackages != null) {
23570                    final int packagesCount = mKeepUninstalledPackages.size();
23571                    for (int i = 0; i < packagesCount; i++) {
23572                        String oldPackage = mKeepUninstalledPackages.get(i);
23573                        if (packageList != null && packageList.contains(oldPackage)) {
23574                            continue;
23575                        }
23576                        if (removedFromList == null) {
23577                            removedFromList = new ArrayList<>();
23578                        }
23579                        removedFromList.add(oldPackage);
23580                    }
23581                }
23582                mKeepUninstalledPackages = new ArrayList<>(packageList);
23583                if (removedFromList != null) {
23584                    final int removedCount = removedFromList.size();
23585                    for (int i = 0; i < removedCount; i++) {
23586                        deletePackageIfUnusedLPr(removedFromList.get(i));
23587                    }
23588                }
23589            }
23590        }
23591
23592        @Override
23593        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23594            synchronized (mPackages) {
23595                return mPermissionManager.isPermissionsReviewRequired(
23596                        mPackages.get(packageName), userId);
23597            }
23598        }
23599
23600        @Override
23601        public PackageInfo getPackageInfo(
23602                String packageName, int flags, int filterCallingUid, int userId) {
23603            return PackageManagerService.this
23604                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23605                            flags, filterCallingUid, userId);
23606        }
23607
23608        @Override
23609        public int getPackageUid(String packageName, int flags, int userId) {
23610            return PackageManagerService.this
23611                    .getPackageUid(packageName, flags, userId);
23612        }
23613
23614        @Override
23615        public ApplicationInfo getApplicationInfo(
23616                String packageName, int flags, int filterCallingUid, int userId) {
23617            return PackageManagerService.this
23618                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23619        }
23620
23621        @Override
23622        public ActivityInfo getActivityInfo(
23623                ComponentName component, int flags, int filterCallingUid, int userId) {
23624            return PackageManagerService.this
23625                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23626        }
23627
23628        @Override
23629        public List<ResolveInfo> queryIntentActivities(
23630                Intent intent, int flags, int filterCallingUid, int userId) {
23631            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23632            return PackageManagerService.this
23633                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23634                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23635        }
23636
23637        @Override
23638        public List<ResolveInfo> queryIntentServices(
23639                Intent intent, int flags, int callingUid, int userId) {
23640            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23641            return PackageManagerService.this
23642                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23643                            false);
23644        }
23645
23646        @Override
23647        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23648                int userId) {
23649            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23650        }
23651
23652        @Override
23653        public ComponentName getDefaultHomeActivity(int userId) {
23654            return PackageManagerService.this.getDefaultHomeActivity(userId);
23655        }
23656
23657        @Override
23658        public void setDeviceAndProfileOwnerPackages(
23659                int deviceOwnerUserId, String deviceOwnerPackage,
23660                SparseArray<String> profileOwnerPackages) {
23661            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23662                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23663        }
23664
23665        @Override
23666        public boolean isPackageDataProtected(int userId, String packageName) {
23667            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23668        }
23669
23670        @Override
23671        public boolean isPackageEphemeral(int userId, String packageName) {
23672            synchronized (mPackages) {
23673                final PackageSetting ps = mSettings.mPackages.get(packageName);
23674                return ps != null ? ps.getInstantApp(userId) : false;
23675            }
23676        }
23677
23678        @Override
23679        public boolean wasPackageEverLaunched(String packageName, int userId) {
23680            synchronized (mPackages) {
23681                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23682            }
23683        }
23684
23685        @Override
23686        public void grantRuntimePermission(String packageName, String permName, int userId,
23687                boolean overridePolicy) {
23688            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23689                    permName, packageName, overridePolicy, getCallingUid(), userId,
23690                    mPermissionCallback);
23691        }
23692
23693        @Override
23694        public void revokeRuntimePermission(String packageName, String permName, int userId,
23695                boolean overridePolicy) {
23696            mPermissionManager.revokeRuntimePermission(
23697                    permName, packageName, overridePolicy, getCallingUid(), userId,
23698                    mPermissionCallback);
23699        }
23700
23701        @Override
23702        public String getNameForUid(int uid) {
23703            return PackageManagerService.this.getNameForUid(uid);
23704        }
23705
23706        @Override
23707        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23708                Intent origIntent, String resolvedType, String callingPackage,
23709                Bundle verificationBundle, int userId) {
23710            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23711                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23712                    userId);
23713        }
23714
23715        @Override
23716        public void grantEphemeralAccess(int userId, Intent intent,
23717                int targetAppId, int ephemeralAppId) {
23718            synchronized (mPackages) {
23719                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23720                        targetAppId, ephemeralAppId);
23721            }
23722        }
23723
23724        @Override
23725        public boolean isInstantAppInstallerComponent(ComponentName component) {
23726            synchronized (mPackages) {
23727                return mInstantAppInstallerActivity != null
23728                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23729            }
23730        }
23731
23732        @Override
23733        public void pruneInstantApps() {
23734            mInstantAppRegistry.pruneInstantApps();
23735        }
23736
23737        @Override
23738        public String getSetupWizardPackageName() {
23739            return mSetupWizardPackage;
23740        }
23741
23742        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23743            if (policy != null) {
23744                mExternalSourcesPolicy = policy;
23745            }
23746        }
23747
23748        @Override
23749        public boolean isPackagePersistent(String packageName) {
23750            synchronized (mPackages) {
23751                PackageParser.Package pkg = mPackages.get(packageName);
23752                return pkg != null
23753                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23754                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23755                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23756                        : false;
23757            }
23758        }
23759
23760        @Override
23761        public boolean isLegacySystemApp(Package pkg) {
23762            synchronized (mPackages) {
23763                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23764                return mPromoteSystemApps
23765                        && ps.isSystem()
23766                        && mExistingSystemPackages.contains(ps.name);
23767            }
23768        }
23769
23770        @Override
23771        public List<PackageInfo> getOverlayPackages(int userId) {
23772            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23773            synchronized (mPackages) {
23774                for (PackageParser.Package p : mPackages.values()) {
23775                    if (p.mOverlayTarget != null) {
23776                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23777                        if (pkg != null) {
23778                            overlayPackages.add(pkg);
23779                        }
23780                    }
23781                }
23782            }
23783            return overlayPackages;
23784        }
23785
23786        @Override
23787        public List<String> getTargetPackageNames(int userId) {
23788            List<String> targetPackages = new ArrayList<>();
23789            synchronized (mPackages) {
23790                for (PackageParser.Package p : mPackages.values()) {
23791                    if (p.mOverlayTarget == null) {
23792                        targetPackages.add(p.packageName);
23793                    }
23794                }
23795            }
23796            return targetPackages;
23797        }
23798
23799        @Override
23800        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23801                @Nullable List<String> overlayPackageNames) {
23802            synchronized (mPackages) {
23803                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23804                    Slog.e(TAG, "failed to find package " + targetPackageName);
23805                    return false;
23806                }
23807                ArrayList<String> overlayPaths = null;
23808                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23809                    final int N = overlayPackageNames.size();
23810                    overlayPaths = new ArrayList<>(N);
23811                    for (int i = 0; i < N; i++) {
23812                        final String packageName = overlayPackageNames.get(i);
23813                        final PackageParser.Package pkg = mPackages.get(packageName);
23814                        if (pkg == null) {
23815                            Slog.e(TAG, "failed to find package " + packageName);
23816                            return false;
23817                        }
23818                        overlayPaths.add(pkg.baseCodePath);
23819                    }
23820                }
23821
23822                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23823                ps.setOverlayPaths(overlayPaths, userId);
23824                return true;
23825            }
23826        }
23827
23828        @Override
23829        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23830                int flags, int userId, boolean resolveForStart) {
23831            return resolveIntentInternal(
23832                    intent, resolvedType, flags, userId, resolveForStart);
23833        }
23834
23835        @Override
23836        public ResolveInfo resolveService(Intent intent, String resolvedType,
23837                int flags, int userId, int callingUid) {
23838            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23839        }
23840
23841        @Override
23842        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23843            return PackageManagerService.this.resolveContentProviderInternal(
23844                    name, flags, userId);
23845        }
23846
23847        @Override
23848        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23849            synchronized (mPackages) {
23850                mIsolatedOwners.put(isolatedUid, ownerUid);
23851            }
23852        }
23853
23854        @Override
23855        public void removeIsolatedUid(int isolatedUid) {
23856            synchronized (mPackages) {
23857                mIsolatedOwners.delete(isolatedUid);
23858            }
23859        }
23860
23861        @Override
23862        public int getUidTargetSdkVersion(int uid) {
23863            synchronized (mPackages) {
23864                return getUidTargetSdkVersionLockedLPr(uid);
23865            }
23866        }
23867
23868        @Override
23869        public int getPackageTargetSdkVersion(String packageName) {
23870            synchronized (mPackages) {
23871                return getPackageTargetSdkVersionLockedLPr(packageName);
23872            }
23873        }
23874
23875        @Override
23876        public boolean canAccessInstantApps(int callingUid, int userId) {
23877            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23878        }
23879
23880        @Override
23881        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23882            synchronized (mPackages) {
23883                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23884            }
23885        }
23886
23887        @Override
23888        public void notifyPackageUse(String packageName, int reason) {
23889            synchronized (mPackages) {
23890                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23891            }
23892        }
23893    }
23894
23895    @Override
23896    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23897        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23898        synchronized (mPackages) {
23899            final long identity = Binder.clearCallingIdentity();
23900            try {
23901                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23902                        packageNames, userId);
23903            } finally {
23904                Binder.restoreCallingIdentity(identity);
23905            }
23906        }
23907    }
23908
23909    @Override
23910    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23911        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23912        synchronized (mPackages) {
23913            final long identity = Binder.clearCallingIdentity();
23914            try {
23915                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23916                        packageNames, userId);
23917            } finally {
23918                Binder.restoreCallingIdentity(identity);
23919            }
23920        }
23921    }
23922
23923    private static void enforceSystemOrPhoneCaller(String tag) {
23924        int callingUid = Binder.getCallingUid();
23925        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23926            throw new SecurityException(
23927                    "Cannot call " + tag + " from UID " + callingUid);
23928        }
23929    }
23930
23931    boolean isHistoricalPackageUsageAvailable() {
23932        return mPackageUsage.isHistoricalPackageUsageAvailable();
23933    }
23934
23935    /**
23936     * Return a <b>copy</b> of the collection of packages known to the package manager.
23937     * @return A copy of the values of mPackages.
23938     */
23939    Collection<PackageParser.Package> getPackages() {
23940        synchronized (mPackages) {
23941            return new ArrayList<>(mPackages.values());
23942        }
23943    }
23944
23945    /**
23946     * Logs process start information (including base APK hash) to the security log.
23947     * @hide
23948     */
23949    @Override
23950    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23951            String apkFile, int pid) {
23952        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23953            return;
23954        }
23955        if (!SecurityLog.isLoggingEnabled()) {
23956            return;
23957        }
23958        Bundle data = new Bundle();
23959        data.putLong("startTimestamp", System.currentTimeMillis());
23960        data.putString("processName", processName);
23961        data.putInt("uid", uid);
23962        data.putString("seinfo", seinfo);
23963        data.putString("apkFile", apkFile);
23964        data.putInt("pid", pid);
23965        Message msg = mProcessLoggingHandler.obtainMessage(
23966                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23967        msg.setData(data);
23968        mProcessLoggingHandler.sendMessage(msg);
23969    }
23970
23971    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23972        return mCompilerStats.getPackageStats(pkgName);
23973    }
23974
23975    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23976        return getOrCreateCompilerPackageStats(pkg.packageName);
23977    }
23978
23979    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23980        return mCompilerStats.getOrCreatePackageStats(pkgName);
23981    }
23982
23983    public void deleteCompilerPackageStats(String pkgName) {
23984        mCompilerStats.deletePackageStats(pkgName);
23985    }
23986
23987    @Override
23988    public int getInstallReason(String packageName, int userId) {
23989        final int callingUid = Binder.getCallingUid();
23990        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23991                true /* requireFullPermission */, false /* checkShell */,
23992                "get install reason");
23993        synchronized (mPackages) {
23994            final PackageSetting ps = mSettings.mPackages.get(packageName);
23995            if (filterAppAccessLPr(ps, callingUid, userId)) {
23996                return PackageManager.INSTALL_REASON_UNKNOWN;
23997            }
23998            if (ps != null) {
23999                return ps.getInstallReason(userId);
24000            }
24001        }
24002        return PackageManager.INSTALL_REASON_UNKNOWN;
24003    }
24004
24005    @Override
24006    public boolean canRequestPackageInstalls(String packageName, int userId) {
24007        return canRequestPackageInstallsInternal(packageName, 0, userId,
24008                true /* throwIfPermNotDeclared*/);
24009    }
24010
24011    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24012            boolean throwIfPermNotDeclared) {
24013        int callingUid = Binder.getCallingUid();
24014        int uid = getPackageUid(packageName, 0, userId);
24015        if (callingUid != uid && callingUid != Process.ROOT_UID
24016                && callingUid != Process.SYSTEM_UID) {
24017            throw new SecurityException(
24018                    "Caller uid " + callingUid + " does not own package " + packageName);
24019        }
24020        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24021        if (info == null) {
24022            return false;
24023        }
24024        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24025            return false;
24026        }
24027        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24028        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24029        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24030            if (throwIfPermNotDeclared) {
24031                throw new SecurityException("Need to declare " + appOpPermission
24032                        + " to call this api");
24033            } else {
24034                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24035                return false;
24036            }
24037        }
24038        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24039            return false;
24040        }
24041        if (mExternalSourcesPolicy != null) {
24042            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24043            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24044                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24045            }
24046        }
24047        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24048    }
24049
24050    @Override
24051    public ComponentName getInstantAppResolverSettingsComponent() {
24052        return mInstantAppResolverSettingsComponent;
24053    }
24054
24055    @Override
24056    public ComponentName getInstantAppInstallerComponent() {
24057        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24058            return null;
24059        }
24060        return mInstantAppInstallerActivity == null
24061                ? null : mInstantAppInstallerActivity.getComponentName();
24062    }
24063
24064    @Override
24065    public String getInstantAppAndroidId(String packageName, int userId) {
24066        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24067                "getInstantAppAndroidId");
24068        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24069                true /* requireFullPermission */, false /* checkShell */,
24070                "getInstantAppAndroidId");
24071        // Make sure the target is an Instant App.
24072        if (!isInstantApp(packageName, userId)) {
24073            return null;
24074        }
24075        synchronized (mPackages) {
24076            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24077        }
24078    }
24079
24080    boolean canHaveOatDir(String packageName) {
24081        synchronized (mPackages) {
24082            PackageParser.Package p = mPackages.get(packageName);
24083            if (p == null) {
24084                return false;
24085            }
24086            return p.canHaveOatDir();
24087        }
24088    }
24089
24090    private String getOatDir(PackageParser.Package pkg) {
24091        if (!pkg.canHaveOatDir()) {
24092            return null;
24093        }
24094        File codePath = new File(pkg.codePath);
24095        if (codePath.isDirectory()) {
24096            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24097        }
24098        return null;
24099    }
24100
24101    void deleteOatArtifactsOfPackage(String packageName) {
24102        final String[] instructionSets;
24103        final List<String> codePaths;
24104        final String oatDir;
24105        final PackageParser.Package pkg;
24106        synchronized (mPackages) {
24107            pkg = mPackages.get(packageName);
24108        }
24109        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24110        codePaths = pkg.getAllCodePaths();
24111        oatDir = getOatDir(pkg);
24112
24113        for (String codePath : codePaths) {
24114            for (String isa : instructionSets) {
24115                try {
24116                    mInstaller.deleteOdex(codePath, isa, oatDir);
24117                } catch (InstallerException e) {
24118                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24119                }
24120            }
24121        }
24122    }
24123
24124    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24125        Set<String> unusedPackages = new HashSet<>();
24126        long currentTimeInMillis = System.currentTimeMillis();
24127        synchronized (mPackages) {
24128            for (PackageParser.Package pkg : mPackages.values()) {
24129                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24130                if (ps == null) {
24131                    continue;
24132                }
24133                PackageDexUsage.PackageUseInfo packageUseInfo =
24134                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24135                if (PackageManagerServiceUtils
24136                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24137                                downgradeTimeThresholdMillis, packageUseInfo,
24138                                pkg.getLatestPackageUseTimeInMills(),
24139                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24140                    unusedPackages.add(pkg.packageName);
24141                }
24142            }
24143        }
24144        return unusedPackages;
24145    }
24146
24147    @Override
24148    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24149            int userId) {
24150        final int callingUid = Binder.getCallingUid();
24151        final int callingAppId = UserHandle.getAppId(callingUid);
24152
24153        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24154                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24155
24156        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24157                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24158            throw new SecurityException("Caller must have the "
24159                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24160        }
24161
24162        synchronized(mPackages) {
24163            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24164            scheduleWritePackageRestrictionsLocked(userId);
24165        }
24166    }
24167
24168    @Nullable
24169    @Override
24170    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24171        final int callingUid = Binder.getCallingUid();
24172        final int callingAppId = UserHandle.getAppId(callingUid);
24173
24174        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24175                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24176
24177        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24178                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24179            throw new SecurityException("Caller must have the "
24180                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24181        }
24182
24183        synchronized(mPackages) {
24184            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24185        }
24186    }
24187}
24188
24189interface PackageSender {
24190    /**
24191     * @param userIds User IDs where the action occurred on a full application
24192     * @param instantUserIds User IDs where the action occurred on an instant application
24193     */
24194    void sendPackageBroadcast(final String action, final String pkg,
24195        final Bundle extras, final int flags, final String targetPkg,
24196        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24197    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24198        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24199    void notifyPackageAdded(String packageName);
24200    void notifyPackageRemoved(String packageName);
24201}
24202