PackageManagerService.java revision cc65194e8e5a284e915176200a846ec75c037d95
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.SignatureSchemeVersion;
180import android.content.pm.PackageStats;
181import android.content.pm.PackageUserState;
182import android.content.pm.ParceledListSlice;
183import android.content.pm.PermissionGroupInfo;
184import android.content.pm.PermissionInfo;
185import android.content.pm.ProviderInfo;
186import android.content.pm.ResolveInfo;
187import android.content.pm.ServiceInfo;
188import android.content.pm.SharedLibraryInfo;
189import android.content.pm.Signature;
190import android.content.pm.UserInfo;
191import android.content.pm.VerifierDeviceIdentity;
192import android.content.pm.VerifierInfo;
193import android.content.pm.VersionedPackage;
194import android.content.pm.dex.ArtManager;
195import android.content.pm.dex.DexMetadataHelper;
196import android.content.pm.dex.IArtManager;
197import android.content.res.Resources;
198import android.database.ContentObserver;
199import android.graphics.Bitmap;
200import android.hardware.display.DisplayManager;
201import android.net.Uri;
202import android.os.Binder;
203import android.os.Build;
204import android.os.Bundle;
205import android.os.Debug;
206import android.os.Environment;
207import android.os.Environment.UserEnvironment;
208import android.os.FileUtils;
209import android.os.Handler;
210import android.os.IBinder;
211import android.os.Looper;
212import android.os.Message;
213import android.os.Parcel;
214import android.os.ParcelFileDescriptor;
215import android.os.PatternMatcher;
216import android.os.Process;
217import android.os.RemoteCallbackList;
218import android.os.RemoteException;
219import android.os.ResultReceiver;
220import android.os.SELinux;
221import android.os.ServiceManager;
222import android.os.ShellCallback;
223import android.os.SystemClock;
224import android.os.SystemProperties;
225import android.os.Trace;
226import android.os.UserHandle;
227import android.os.UserManager;
228import android.os.UserManagerInternal;
229import android.os.storage.IStorageManager;
230import android.os.storage.StorageEventListener;
231import android.os.storage.StorageManager;
232import android.os.storage.StorageManagerInternal;
233import android.os.storage.VolumeInfo;
234import android.os.storage.VolumeRecord;
235import android.provider.Settings.Global;
236import android.provider.Settings.Secure;
237import android.security.KeyStore;
238import android.security.SystemKeyStore;
239import android.service.pm.PackageServiceDumpProto;
240import android.system.ErrnoException;
241import android.system.Os;
242import android.text.TextUtils;
243import android.text.format.DateUtils;
244import android.util.ArrayMap;
245import android.util.ArraySet;
246import android.util.Base64;
247import android.util.ByteStringUtils;
248import android.util.DisplayMetrics;
249import android.util.EventLog;
250import android.util.ExceptionUtils;
251import android.util.Log;
252import android.util.LogPrinter;
253import android.util.LongSparseArray;
254import android.util.LongSparseLongArray;
255import android.util.MathUtils;
256import android.util.PackageUtils;
257import android.util.Pair;
258import android.util.PrintStreamPrinter;
259import android.util.Slog;
260import android.util.SparseArray;
261import android.util.SparseBooleanArray;
262import android.util.SparseIntArray;
263import android.util.TimingsTraceLog;
264import android.util.Xml;
265import android.util.jar.StrictJarFile;
266import android.util.proto.ProtoOutputStream;
267import android.view.Display;
268
269import com.android.internal.R;
270import com.android.internal.annotations.GuardedBy;
271import com.android.internal.app.IMediaContainerService;
272import com.android.internal.app.ResolverActivity;
273import com.android.internal.content.NativeLibraryHelper;
274import com.android.internal.content.PackageHelper;
275import com.android.internal.logging.MetricsLogger;
276import com.android.internal.os.IParcelFileDescriptorFactory;
277import com.android.internal.os.SomeArgs;
278import com.android.internal.os.Zygote;
279import com.android.internal.telephony.CarrierAppUtils;
280import com.android.internal.util.ArrayUtils;
281import com.android.internal.util.ConcurrentUtils;
282import com.android.internal.util.DumpUtils;
283import com.android.internal.util.FastXmlSerializer;
284import com.android.internal.util.IndentingPrintWriter;
285import com.android.internal.util.Preconditions;
286import com.android.internal.util.XmlUtils;
287import com.android.server.AttributeCache;
288import com.android.server.DeviceIdleController;
289import com.android.server.EventLogTags;
290import com.android.server.FgThread;
291import com.android.server.IntentResolver;
292import com.android.server.LocalServices;
293import com.android.server.LockGuard;
294import com.android.server.ServiceThread;
295import com.android.server.SystemConfig;
296import com.android.server.SystemServerInitThreadPool;
297import com.android.server.Watchdog;
298import com.android.server.net.NetworkPolicyManagerInternal;
299import com.android.server.pm.Installer.InstallerException;
300import com.android.server.pm.Settings.DatabaseVersion;
301import com.android.server.pm.Settings.VersionInfo;
302import com.android.server.pm.dex.ArtManagerService;
303import com.android.server.pm.dex.DexLogger;
304import com.android.server.pm.dex.DexManager;
305import com.android.server.pm.dex.DexoptOptions;
306import com.android.server.pm.dex.PackageDexUsage;
307import com.android.server.pm.permission.BasePermission;
308import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
309import com.android.server.pm.permission.PermissionManagerService;
310import com.android.server.pm.permission.PermissionManagerInternal;
311import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
312import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
313import com.android.server.pm.permission.PermissionsState;
314import com.android.server.pm.permission.PermissionsState.PermissionState;
315import com.android.server.security.VerityUtils;
316import com.android.server.storage.DeviceStorageMonitorInternal;
317
318import dalvik.system.CloseGuard;
319import dalvik.system.VMRuntime;
320
321import libcore.io.IoUtils;
322
323import org.xmlpull.v1.XmlPullParser;
324import org.xmlpull.v1.XmlPullParserException;
325import org.xmlpull.v1.XmlSerializer;
326
327import java.io.BufferedOutputStream;
328import java.io.ByteArrayInputStream;
329import java.io.ByteArrayOutputStream;
330import java.io.File;
331import java.io.FileDescriptor;
332import java.io.FileInputStream;
333import java.io.FileOutputStream;
334import java.io.FilenameFilter;
335import java.io.IOException;
336import java.io.PrintWriter;
337import java.lang.annotation.Retention;
338import java.lang.annotation.RetentionPolicy;
339import java.nio.charset.StandardCharsets;
340import java.security.DigestException;
341import java.security.DigestInputStream;
342import java.security.MessageDigest;
343import java.security.NoSuchAlgorithmException;
344import java.security.PublicKey;
345import java.security.SecureRandom;
346import java.security.cert.CertificateException;
347import java.util.ArrayList;
348import java.util.Arrays;
349import java.util.Collection;
350import java.util.Collections;
351import java.util.Comparator;
352import java.util.HashMap;
353import java.util.HashSet;
354import java.util.Iterator;
355import java.util.LinkedHashSet;
356import java.util.List;
357import java.util.Map;
358import java.util.Objects;
359import java.util.Set;
360import java.util.concurrent.CountDownLatch;
361import java.util.concurrent.Future;
362import java.util.concurrent.TimeUnit;
363import java.util.concurrent.atomic.AtomicBoolean;
364import java.util.concurrent.atomic.AtomicInteger;
365
366/**
367 * Keep track of all those APKs everywhere.
368 * <p>
369 * Internally there are two important locks:
370 * <ul>
371 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
372 * and other related state. It is a fine-grained lock that should only be held
373 * momentarily, as it's one of the most contended locks in the system.
374 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
375 * operations typically involve heavy lifting of application data on disk. Since
376 * {@code installd} is single-threaded, and it's operations can often be slow,
377 * this lock should never be acquired while already holding {@link #mPackages}.
378 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
379 * holding {@link #mInstallLock}.
380 * </ul>
381 * Many internal methods rely on the caller to hold the appropriate locks, and
382 * this contract is expressed through method name suffixes:
383 * <ul>
384 * <li>fooLI(): the caller must hold {@link #mInstallLock}
385 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
386 * being modified must be frozen
387 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
388 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
389 * </ul>
390 * <p>
391 * Because this class is very central to the platform's security; please run all
392 * CTS and unit tests whenever making modifications:
393 *
394 * <pre>
395 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
396 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
397 * </pre>
398 */
399public class PackageManagerService extends IPackageManager.Stub
400        implements PackageSender {
401    static final String TAG = "PackageManager";
402    public static final boolean DEBUG_SETTINGS = false;
403    static final boolean DEBUG_PREFERRED = false;
404    static final boolean DEBUG_UPGRADE = false;
405    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
406    private static final boolean DEBUG_BACKUP = false;
407    public static final boolean DEBUG_INSTALL = false;
408    public static final boolean DEBUG_REMOVE = false;
409    private static final boolean DEBUG_BROADCASTS = false;
410    private static final boolean DEBUG_SHOW_INFO = false;
411    private static final boolean DEBUG_PACKAGE_INFO = false;
412    private static final boolean DEBUG_INTENT_MATCHING = false;
413    public static final boolean DEBUG_PACKAGE_SCANNING = false;
414    private static final boolean DEBUG_VERIFY = false;
415    private static final boolean DEBUG_FILTERS = false;
416    public static final boolean DEBUG_PERMISSIONS = false;
417    private static final boolean DEBUG_SHARED_LIBRARIES = false;
418    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
419
420    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
421    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
422    // user, but by default initialize to this.
423    public static final boolean DEBUG_DEXOPT = false;
424
425    private static final boolean DEBUG_ABI_SELECTION = false;
426    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
427    private static final boolean DEBUG_TRIAGED_MISSING = false;
428    private static final boolean DEBUG_APP_DATA = false;
429
430    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
431    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
432
433    private static final boolean HIDE_EPHEMERAL_APIS = false;
434
435    private static final boolean ENABLE_FREE_CACHE_V2 =
436            SystemProperties.getBoolean("fw.free_cache_v2", true);
437
438    private static final int RADIO_UID = Process.PHONE_UID;
439    private static final int LOG_UID = Process.LOG_UID;
440    private static final int NFC_UID = Process.NFC_UID;
441    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
442    private static final int SHELL_UID = Process.SHELL_UID;
443    private static final int SE_UID = Process.SE_UID;
444
445    // Suffix used during package installation when copying/moving
446    // package apks to install directory.
447    private static final String INSTALL_PACKAGE_SUFFIX = "-";
448
449    static final int SCAN_NO_DEX = 1<<0;
450    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
451    static final int SCAN_NEW_INSTALL = 1<<2;
452    static final int SCAN_UPDATE_TIME = 1<<3;
453    static final int SCAN_BOOTING = 1<<4;
454    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
455    static final int SCAN_REQUIRE_KNOWN = 1<<7;
456    static final int SCAN_MOVE = 1<<8;
457    static final int SCAN_INITIAL = 1<<9;
458    static final int SCAN_CHECK_ONLY = 1<<10;
459    static final int SCAN_DONT_KILL_APP = 1<<11;
460    static final int SCAN_IGNORE_FROZEN = 1<<12;
461    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
462    static final int SCAN_AS_INSTANT_APP = 1<<14;
463    static final int SCAN_AS_FULL_APP = 1<<15;
464    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
465    static final int SCAN_AS_SYSTEM = 1<<17;
466    static final int SCAN_AS_PRIVILEGED = 1<<18;
467    static final int SCAN_AS_OEM = 1<<19;
468    static final int SCAN_AS_VENDOR = 1<<20;
469    static final int SCAN_AS_PRODUCT = 1<<21;
470
471    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
472            SCAN_NO_DEX,
473            SCAN_UPDATE_SIGNATURE,
474            SCAN_NEW_INSTALL,
475            SCAN_UPDATE_TIME,
476            SCAN_BOOTING,
477            SCAN_DELETE_DATA_ON_FAILURES,
478            SCAN_REQUIRE_KNOWN,
479            SCAN_MOVE,
480            SCAN_INITIAL,
481            SCAN_CHECK_ONLY,
482            SCAN_DONT_KILL_APP,
483            SCAN_IGNORE_FROZEN,
484            SCAN_FIRST_BOOT_OR_UPGRADE,
485            SCAN_AS_INSTANT_APP,
486            SCAN_AS_FULL_APP,
487            SCAN_AS_VIRTUAL_PRELOAD,
488    })
489    @Retention(RetentionPolicy.SOURCE)
490    public @interface ScanFlags {}
491
492    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
493    /** Extension of the compressed packages */
494    public final static String COMPRESSED_EXTENSION = ".gz";
495    /** Suffix of stub packages on the system partition */
496    public final static String STUB_SUFFIX = "-Stub";
497
498    private static final int[] EMPTY_INT_ARRAY = new int[0];
499
500    private static final int TYPE_UNKNOWN = 0;
501    private static final int TYPE_ACTIVITY = 1;
502    private static final int TYPE_RECEIVER = 2;
503    private static final int TYPE_SERVICE = 3;
504    private static final int TYPE_PROVIDER = 4;
505    @IntDef(prefix = { "TYPE_" }, value = {
506            TYPE_UNKNOWN,
507            TYPE_ACTIVITY,
508            TYPE_RECEIVER,
509            TYPE_SERVICE,
510            TYPE_PROVIDER,
511    })
512    @Retention(RetentionPolicy.SOURCE)
513    public @interface ComponentType {}
514
515    /**
516     * Timeout (in milliseconds) after which the watchdog should declare that
517     * our handler thread is wedged.  The usual default for such things is one
518     * minute but we sometimes do very lengthy I/O operations on this thread,
519     * such as installing multi-gigabyte applications, so ours needs to be longer.
520     */
521    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
522
523    /**
524     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
525     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
526     * settings entry if available, otherwise we use the hardcoded default.  If it's been
527     * more than this long since the last fstrim, we force one during the boot sequence.
528     *
529     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
530     * one gets run at the next available charging+idle time.  This final mandatory
531     * no-fstrim check kicks in only of the other scheduling criteria is never met.
532     */
533    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
534
535    /**
536     * Whether verification is enabled by default.
537     */
538    private static final boolean DEFAULT_VERIFY_ENABLE = true;
539
540    /**
541     * The default maximum time to wait for the verification agent to return in
542     * milliseconds.
543     */
544    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
545
546    /**
547     * The default response for package verification timeout.
548     *
549     * This can be either PackageManager.VERIFICATION_ALLOW or
550     * PackageManager.VERIFICATION_REJECT.
551     */
552    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
553
554    public static final String PLATFORM_PACKAGE_NAME = "android";
555
556    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
557
558    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
559            DEFAULT_CONTAINER_PACKAGE,
560            "com.android.defcontainer.DefaultContainerService");
561
562    private static final String KILL_APP_REASON_GIDS_CHANGED =
563            "permission grant or revoke changed gids";
564
565    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
566            "permissions revoked";
567
568    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
569
570    private static final String PACKAGE_SCHEME = "package";
571
572    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
573
574    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
575
576    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
577
578    /** Canonical intent used to identify what counts as a "web browser" app */
579    private static final Intent sBrowserIntent;
580    static {
581        sBrowserIntent = new Intent();
582        sBrowserIntent.setAction(Intent.ACTION_VIEW);
583        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
584        sBrowserIntent.setData(Uri.parse("http:"));
585        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
586    }
587
588    /**
589     * The set of all protected actions [i.e. those actions for which a high priority
590     * intent filter is disallowed].
591     */
592    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
593    static {
594        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
595        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
596        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
597        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
598    }
599
600    // Compilation reasons.
601    public static final int REASON_FIRST_BOOT = 0;
602    public static final int REASON_BOOT = 1;
603    public static final int REASON_INSTALL = 2;
604    public static final int REASON_BACKGROUND_DEXOPT = 3;
605    public static final int REASON_AB_OTA = 4;
606    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
607    public static final int REASON_SHARED = 6;
608
609    public static final int REASON_LAST = REASON_SHARED;
610
611    /**
612     * Version number for the package parser cache. Increment this whenever the format or
613     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
614     */
615    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
616
617    /**
618     * Whether the package parser cache is enabled.
619     */
620    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
621
622    /**
623     * Permissions required in order to receive instant application lifecycle broadcasts.
624     */
625    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
626            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
627
628    final ServiceThread mHandlerThread;
629
630    final PackageHandler mHandler;
631
632    private final ProcessLoggingHandler mProcessLoggingHandler;
633
634    /**
635     * Messages for {@link #mHandler} that need to wait for system ready before
636     * being dispatched.
637     */
638    private ArrayList<Message> mPostSystemReadyMessages;
639
640    final int mSdkVersion = Build.VERSION.SDK_INT;
641
642    final Context mContext;
643    final boolean mFactoryTest;
644    final boolean mOnlyCore;
645    final DisplayMetrics mMetrics;
646    final int mDefParseFlags;
647    final String[] mSeparateProcesses;
648    final boolean mIsUpgrade;
649    final boolean mIsPreNUpgrade;
650    final boolean mIsPreNMR1Upgrade;
651
652    // Have we told the Activity Manager to whitelist the default container service by uid yet?
653    @GuardedBy("mPackages")
654    boolean mDefaultContainerWhitelisted = false;
655
656    @GuardedBy("mPackages")
657    private boolean mDexOptDialogShown;
658
659    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
660    // LOCK HELD.  Can be called with mInstallLock held.
661    @GuardedBy("mInstallLock")
662    final Installer mInstaller;
663
664    /** Directory where installed applications are stored */
665    private static final File sAppInstallDir =
666            new File(Environment.getDataDirectory(), "app");
667    /** Directory where installed application's 32-bit native libraries are copied. */
668    private static final File sAppLib32InstallDir =
669            new File(Environment.getDataDirectory(), "app-lib");
670    /** Directory where code and non-resource assets of forward-locked applications are stored */
671    private static final File sDrmAppPrivateInstallDir =
672            new File(Environment.getDataDirectory(), "app-private");
673
674    // ----------------------------------------------------------------
675
676    // Lock for state used when installing and doing other long running
677    // operations.  Methods that must be called with this lock held have
678    // the suffix "LI".
679    final Object mInstallLock = new Object();
680
681    // ----------------------------------------------------------------
682
683    // Keys are String (package name), values are Package.  This also serves
684    // as the lock for the global state.  Methods that must be called with
685    // this lock held have the prefix "LP".
686    @GuardedBy("mPackages")
687    final ArrayMap<String, PackageParser.Package> mPackages =
688            new ArrayMap<String, PackageParser.Package>();
689
690    final ArrayMap<String, Set<String>> mKnownCodebase =
691            new ArrayMap<String, Set<String>>();
692
693    // Keys are isolated uids and values are the uid of the application
694    // that created the isolated proccess.
695    @GuardedBy("mPackages")
696    final SparseIntArray mIsolatedOwners = new SparseIntArray();
697
698    /**
699     * Tracks new system packages [received in an OTA] that we expect to
700     * find updated user-installed versions. Keys are package name, values
701     * are package location.
702     */
703    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
704    /**
705     * Tracks high priority intent filters for protected actions. During boot, certain
706     * filter actions are protected and should never be allowed to have a high priority
707     * intent filter for them. However, there is one, and only one exception -- the
708     * setup wizard. It must be able to define a high priority intent filter for these
709     * actions to ensure there are no escapes from the wizard. We need to delay processing
710     * of these during boot as we need to look at all of the system packages in order
711     * to know which component is the setup wizard.
712     */
713    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
714    /**
715     * Whether or not processing protected filters should be deferred.
716     */
717    private boolean mDeferProtectedFilters = true;
718
719    /**
720     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
721     */
722    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
723    /**
724     * Whether or not system app permissions should be promoted from install to runtime.
725     */
726    boolean mPromoteSystemApps;
727
728    @GuardedBy("mPackages")
729    final Settings mSettings;
730
731    /**
732     * Set of package names that are currently "frozen", which means active
733     * surgery is being done on the code/data for that package. The platform
734     * will refuse to launch frozen packages to avoid race conditions.
735     *
736     * @see PackageFreezer
737     */
738    @GuardedBy("mPackages")
739    final ArraySet<String> mFrozenPackages = new ArraySet<>();
740
741    final ProtectedPackages mProtectedPackages;
742
743    @GuardedBy("mLoadedVolumes")
744    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
745
746    boolean mFirstBoot;
747
748    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
749
750    @GuardedBy("mAvailableFeatures")
751    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
752
753    private final InstantAppRegistry mInstantAppRegistry;
754
755    @GuardedBy("mPackages")
756    int mChangedPackagesSequenceNumber;
757    /**
758     * List of changed [installed, removed or updated] packages.
759     * mapping from user id -> sequence number -> package name
760     */
761    @GuardedBy("mPackages")
762    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
763    /**
764     * The sequence number of the last change to a package.
765     * mapping from user id -> package name -> sequence number
766     */
767    @GuardedBy("mPackages")
768    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
769
770    @GuardedBy("mPackages")
771    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
772
773    class PackageParserCallback implements PackageParser.Callback {
774        @Override public final boolean hasFeature(String feature) {
775            return PackageManagerService.this.hasSystemFeature(feature, 0);
776        }
777
778        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
779                Collection<PackageParser.Package> allPackages, String targetPackageName) {
780            List<PackageParser.Package> overlayPackages = null;
781            for (PackageParser.Package p : allPackages) {
782                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
783                    if (overlayPackages == null) {
784                        overlayPackages = new ArrayList<PackageParser.Package>();
785                    }
786                    overlayPackages.add(p);
787                }
788            }
789            if (overlayPackages != null) {
790                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
791                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
792                        return p1.mOverlayPriority - p2.mOverlayPriority;
793                    }
794                };
795                Collections.sort(overlayPackages, cmp);
796            }
797            return overlayPackages;
798        }
799
800        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
801                String targetPackageName, String targetPath) {
802            if ("android".equals(targetPackageName)) {
803                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
804                // native AssetManager.
805                return null;
806            }
807            List<PackageParser.Package> overlayPackages =
808                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
809            if (overlayPackages == null || overlayPackages.isEmpty()) {
810                return null;
811            }
812            List<String> overlayPathList = null;
813            for (PackageParser.Package overlayPackage : overlayPackages) {
814                if (targetPath == null) {
815                    if (overlayPathList == null) {
816                        overlayPathList = new ArrayList<String>();
817                    }
818                    overlayPathList.add(overlayPackage.baseCodePath);
819                    continue;
820                }
821
822                try {
823                    // Creates idmaps for system to parse correctly the Android manifest of the
824                    // target package.
825                    //
826                    // OverlayManagerService will update each of them with a correct gid from its
827                    // target package app id.
828                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
829                            UserHandle.getSharedAppGid(
830                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
831                    if (overlayPathList == null) {
832                        overlayPathList = new ArrayList<String>();
833                    }
834                    overlayPathList.add(overlayPackage.baseCodePath);
835                } catch (InstallerException e) {
836                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
837                            overlayPackage.baseCodePath);
838                }
839            }
840            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
841        }
842
843        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
844            synchronized (mPackages) {
845                return getStaticOverlayPathsLocked(
846                        mPackages.values(), targetPackageName, targetPath);
847            }
848        }
849
850        @Override public final String[] getOverlayApks(String targetPackageName) {
851            return getStaticOverlayPaths(targetPackageName, null);
852        }
853
854        @Override public final String[] getOverlayPaths(String targetPackageName,
855                String targetPath) {
856            return getStaticOverlayPaths(targetPackageName, targetPath);
857        }
858    }
859
860    class ParallelPackageParserCallback extends PackageParserCallback {
861        List<PackageParser.Package> mOverlayPackages = null;
862
863        void findStaticOverlayPackages() {
864            synchronized (mPackages) {
865                for (PackageParser.Package p : mPackages.values()) {
866                    if (p.mOverlayIsStatic) {
867                        if (mOverlayPackages == null) {
868                            mOverlayPackages = new ArrayList<PackageParser.Package>();
869                        }
870                        mOverlayPackages.add(p);
871                    }
872                }
873            }
874        }
875
876        @Override
877        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
878            // We can trust mOverlayPackages without holding mPackages because package uninstall
879            // can't happen while running parallel parsing.
880            // Moreover holding mPackages on each parsing thread causes dead-lock.
881            return mOverlayPackages == null ? null :
882                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
883        }
884    }
885
886    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
887    final ParallelPackageParserCallback mParallelPackageParserCallback =
888            new ParallelPackageParserCallback();
889
890    public static final class SharedLibraryEntry {
891        public final @Nullable String path;
892        public final @Nullable String apk;
893        public final @NonNull SharedLibraryInfo info;
894
895        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
896                String declaringPackageName, long declaringPackageVersionCode) {
897            path = _path;
898            apk = _apk;
899            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
900                    declaringPackageName, declaringPackageVersionCode), null);
901        }
902    }
903
904    // Currently known shared libraries.
905    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
906    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
907            new ArrayMap<>();
908
909    // All available activities, for your resolving pleasure.
910    final ActivityIntentResolver mActivities =
911            new ActivityIntentResolver();
912
913    // All available receivers, for your resolving pleasure.
914    final ActivityIntentResolver mReceivers =
915            new ActivityIntentResolver();
916
917    // All available services, for your resolving pleasure.
918    final ServiceIntentResolver mServices = new ServiceIntentResolver();
919
920    // All available providers, for your resolving pleasure.
921    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
922
923    // Mapping from provider base names (first directory in content URI codePath)
924    // to the provider information.
925    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
926            new ArrayMap<String, PackageParser.Provider>();
927
928    // Mapping from instrumentation class names to info about them.
929    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
930            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
931
932    // Packages whose data we have transfered into another package, thus
933    // should no longer exist.
934    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
935
936    // Broadcast actions that are only available to the system.
937    @GuardedBy("mProtectedBroadcasts")
938    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
939
940    /** List of packages waiting for verification. */
941    final SparseArray<PackageVerificationState> mPendingVerification
942            = new SparseArray<PackageVerificationState>();
943
944    final PackageInstallerService mInstallerService;
945
946    final ArtManagerService mArtManagerService;
947
948    private final PackageDexOptimizer mPackageDexOptimizer;
949    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
950    // is used by other apps).
951    private final DexManager mDexManager;
952
953    private AtomicInteger mNextMoveId = new AtomicInteger();
954    private final MoveCallbacks mMoveCallbacks;
955
956    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
957
958    // Cache of users who need badging.
959    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
960
961    /** Token for keys in mPendingVerification. */
962    private int mPendingVerificationToken = 0;
963
964    volatile boolean mSystemReady;
965    volatile boolean mSafeMode;
966    volatile boolean mHasSystemUidErrors;
967    private volatile boolean mEphemeralAppsDisabled;
968
969    ApplicationInfo mAndroidApplication;
970    final ActivityInfo mResolveActivity = new ActivityInfo();
971    final ResolveInfo mResolveInfo = new ResolveInfo();
972    ComponentName mResolveComponentName;
973    PackageParser.Package mPlatformPackage;
974    ComponentName mCustomResolverComponentName;
975
976    boolean mResolverReplaced = false;
977
978    private final @Nullable ComponentName mIntentFilterVerifierComponent;
979    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
980
981    private int mIntentFilterVerificationToken = 0;
982
983    /** The service connection to the ephemeral resolver */
984    final InstantAppResolverConnection mInstantAppResolverConnection;
985    /** Component used to show resolver settings for Instant Apps */
986    final ComponentName mInstantAppResolverSettingsComponent;
987
988    /** Activity used to install instant applications */
989    ActivityInfo mInstantAppInstallerActivity;
990    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
991
992    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
993            = new SparseArray<IntentFilterVerificationState>();
994
995    // TODO remove this and go through mPermissonManager directly
996    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
997    private final PermissionManagerInternal mPermissionManager;
998
999    // List of packages names to keep cached, even if they are uninstalled for all users
1000    private List<String> mKeepUninstalledPackages;
1001
1002    private UserManagerInternal mUserManagerInternal;
1003    private ActivityManagerInternal mActivityManagerInternal;
1004
1005    private DeviceIdleController.LocalService mDeviceIdleController;
1006
1007    private File mCacheDir;
1008
1009    private Future<?> mPrepareAppDataFuture;
1010
1011    private static class IFVerificationParams {
1012        PackageParser.Package pkg;
1013        boolean replacing;
1014        int userId;
1015        int verifierUid;
1016
1017        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1018                int _userId, int _verifierUid) {
1019            pkg = _pkg;
1020            replacing = _replacing;
1021            userId = _userId;
1022            replacing = _replacing;
1023            verifierUid = _verifierUid;
1024        }
1025    }
1026
1027    private interface IntentFilterVerifier<T extends IntentFilter> {
1028        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1029                                               T filter, String packageName);
1030        void startVerifications(int userId);
1031        void receiveVerificationResponse(int verificationId);
1032    }
1033
1034    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1035        private Context mContext;
1036        private ComponentName mIntentFilterVerifierComponent;
1037        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1038
1039        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1040            mContext = context;
1041            mIntentFilterVerifierComponent = verifierComponent;
1042        }
1043
1044        private String getDefaultScheme() {
1045            return IntentFilter.SCHEME_HTTPS;
1046        }
1047
1048        @Override
1049        public void startVerifications(int userId) {
1050            // Launch verifications requests
1051            int count = mCurrentIntentFilterVerifications.size();
1052            for (int n=0; n<count; n++) {
1053                int verificationId = mCurrentIntentFilterVerifications.get(n);
1054                final IntentFilterVerificationState ivs =
1055                        mIntentFilterVerificationStates.get(verificationId);
1056
1057                String packageName = ivs.getPackageName();
1058
1059                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1060                final int filterCount = filters.size();
1061                ArraySet<String> domainsSet = new ArraySet<>();
1062                for (int m=0; m<filterCount; m++) {
1063                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1064                    domainsSet.addAll(filter.getHostsList());
1065                }
1066                synchronized (mPackages) {
1067                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1068                            packageName, domainsSet) != null) {
1069                        scheduleWriteSettingsLocked();
1070                    }
1071                }
1072                sendVerificationRequest(verificationId, ivs);
1073            }
1074            mCurrentIntentFilterVerifications.clear();
1075        }
1076
1077        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1078            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1079            verificationIntent.putExtra(
1080                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1081                    verificationId);
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1084                    getDefaultScheme());
1085            verificationIntent.putExtra(
1086                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1087                    ivs.getHostsString());
1088            verificationIntent.putExtra(
1089                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1090                    ivs.getPackageName());
1091            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1092            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1093
1094            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1095            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1096                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1097                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1098
1099            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1100            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1101                    "Sending IntentFilter verification broadcast");
1102        }
1103
1104        public void receiveVerificationResponse(int verificationId) {
1105            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1106
1107            final boolean verified = ivs.isVerified();
1108
1109            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1110            final int count = filters.size();
1111            if (DEBUG_DOMAIN_VERIFICATION) {
1112                Slog.i(TAG, "Received verification response " + verificationId
1113                        + " for " + count + " filters, verified=" + verified);
1114            }
1115            for (int n=0; n<count; n++) {
1116                PackageParser.ActivityIntentInfo filter = filters.get(n);
1117                filter.setVerified(verified);
1118
1119                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1120                        + " verified with result:" + verified + " and hosts:"
1121                        + ivs.getHostsString());
1122            }
1123
1124            mIntentFilterVerificationStates.remove(verificationId);
1125
1126            final String packageName = ivs.getPackageName();
1127            IntentFilterVerificationInfo ivi = null;
1128
1129            synchronized (mPackages) {
1130                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1131            }
1132            if (ivi == null) {
1133                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1134                        + verificationId + " packageName:" + packageName);
1135                return;
1136            }
1137            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1138                    "Updating IntentFilterVerificationInfo for package " + packageName
1139                            +" verificationId:" + verificationId);
1140
1141            synchronized (mPackages) {
1142                if (verified) {
1143                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1144                } else {
1145                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1146                }
1147                scheduleWriteSettingsLocked();
1148
1149                final int userId = ivs.getUserId();
1150                if (userId != UserHandle.USER_ALL) {
1151                    final int userStatus =
1152                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1153
1154                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1155                    boolean needUpdate = false;
1156
1157                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1158                    // already been set by the User thru the Disambiguation dialog
1159                    switch (userStatus) {
1160                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1161                            if (verified) {
1162                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1163                            } else {
1164                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1165                            }
1166                            needUpdate = true;
1167                            break;
1168
1169                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1170                            if (verified) {
1171                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1172                                needUpdate = true;
1173                            }
1174                            break;
1175
1176                        default:
1177                            // Nothing to do
1178                    }
1179
1180                    if (needUpdate) {
1181                        mSettings.updateIntentFilterVerificationStatusLPw(
1182                                packageName, updatedStatus, userId);
1183                        scheduleWritePackageRestrictionsLocked(userId);
1184                    }
1185                }
1186            }
1187        }
1188
1189        @Override
1190        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1191                    ActivityIntentInfo filter, String packageName) {
1192            if (!hasValidDomains(filter)) {
1193                return false;
1194            }
1195            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1196            if (ivs == null) {
1197                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1198                        packageName);
1199            }
1200            if (DEBUG_DOMAIN_VERIFICATION) {
1201                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1202            }
1203            ivs.addFilter(filter);
1204            return true;
1205        }
1206
1207        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1208                int userId, int verificationId, String packageName) {
1209            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1210                    verifierUid, userId, packageName);
1211            ivs.setPendingState();
1212            synchronized (mPackages) {
1213                mIntentFilterVerificationStates.append(verificationId, ivs);
1214                mCurrentIntentFilterVerifications.add(verificationId);
1215            }
1216            return ivs;
1217        }
1218    }
1219
1220    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1221        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1222                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1223                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1224    }
1225
1226    // Set of pending broadcasts for aggregating enable/disable of components.
1227    static class PendingPackageBroadcasts {
1228        // for each user id, a map of <package name -> components within that package>
1229        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1230
1231        public PendingPackageBroadcasts() {
1232            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1233        }
1234
1235        public ArrayList<String> get(int userId, String packageName) {
1236            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1237            return packages.get(packageName);
1238        }
1239
1240        public void put(int userId, String packageName, ArrayList<String> components) {
1241            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1242            packages.put(packageName, components);
1243        }
1244
1245        public void remove(int userId, String packageName) {
1246            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1247            if (packages != null) {
1248                packages.remove(packageName);
1249            }
1250        }
1251
1252        public void remove(int userId) {
1253            mUidMap.remove(userId);
1254        }
1255
1256        public int userIdCount() {
1257            return mUidMap.size();
1258        }
1259
1260        public int userIdAt(int n) {
1261            return mUidMap.keyAt(n);
1262        }
1263
1264        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1265            return mUidMap.get(userId);
1266        }
1267
1268        public int size() {
1269            // total number of pending broadcast entries across all userIds
1270            int num = 0;
1271            for (int i = 0; i< mUidMap.size(); i++) {
1272                num += mUidMap.valueAt(i).size();
1273            }
1274            return num;
1275        }
1276
1277        public void clear() {
1278            mUidMap.clear();
1279        }
1280
1281        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1282            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1283            if (map == null) {
1284                map = new ArrayMap<String, ArrayList<String>>();
1285                mUidMap.put(userId, map);
1286            }
1287            return map;
1288        }
1289    }
1290    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1291
1292    // Service Connection to remote media container service to copy
1293    // package uri's from external media onto secure containers
1294    // or internal storage.
1295    private IMediaContainerService mContainerService = null;
1296
1297    static final int SEND_PENDING_BROADCAST = 1;
1298    static final int MCS_BOUND = 3;
1299    static final int END_COPY = 4;
1300    static final int INIT_COPY = 5;
1301    static final int MCS_UNBIND = 6;
1302    static final int START_CLEANING_PACKAGE = 7;
1303    static final int FIND_INSTALL_LOC = 8;
1304    static final int POST_INSTALL = 9;
1305    static final int MCS_RECONNECT = 10;
1306    static final int MCS_GIVE_UP = 11;
1307    static final int WRITE_SETTINGS = 13;
1308    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1309    static final int PACKAGE_VERIFIED = 15;
1310    static final int CHECK_PENDING_VERIFICATION = 16;
1311    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1312    static final int INTENT_FILTER_VERIFIED = 18;
1313    static final int WRITE_PACKAGE_LIST = 19;
1314    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1315
1316    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1317
1318    // Delay time in millisecs
1319    static final int BROADCAST_DELAY = 10 * 1000;
1320
1321    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1322            2 * 60 * 60 * 1000L; /* two hours */
1323
1324    static UserManagerService sUserManager;
1325
1326    // Stores a list of users whose package restrictions file needs to be updated
1327    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1328
1329    final private DefaultContainerConnection mDefContainerConn =
1330            new DefaultContainerConnection();
1331    class DefaultContainerConnection implements ServiceConnection {
1332        public void onServiceConnected(ComponentName name, IBinder service) {
1333            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1334            final IMediaContainerService imcs = IMediaContainerService.Stub
1335                    .asInterface(Binder.allowBlocking(service));
1336            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1337        }
1338
1339        public void onServiceDisconnected(ComponentName name) {
1340            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1341        }
1342    }
1343
1344    // Recordkeeping of restore-after-install operations that are currently in flight
1345    // between the Package Manager and the Backup Manager
1346    static class PostInstallData {
1347        public InstallArgs args;
1348        public PackageInstalledInfo res;
1349
1350        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1351            args = _a;
1352            res = _r;
1353        }
1354    }
1355
1356    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1357    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1358
1359    // XML tags for backup/restore of various bits of state
1360    private static final String TAG_PREFERRED_BACKUP = "pa";
1361    private static final String TAG_DEFAULT_APPS = "da";
1362    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1363
1364    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1365    private static final String TAG_ALL_GRANTS = "rt-grants";
1366    private static final String TAG_GRANT = "grant";
1367    private static final String ATTR_PACKAGE_NAME = "pkg";
1368
1369    private static final String TAG_PERMISSION = "perm";
1370    private static final String ATTR_PERMISSION_NAME = "name";
1371    private static final String ATTR_IS_GRANTED = "g";
1372    private static final String ATTR_USER_SET = "set";
1373    private static final String ATTR_USER_FIXED = "fixed";
1374    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1375
1376    // System/policy permission grants are not backed up
1377    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1378            FLAG_PERMISSION_POLICY_FIXED
1379            | FLAG_PERMISSION_SYSTEM_FIXED
1380            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1381
1382    // And we back up these user-adjusted states
1383    private static final int USER_RUNTIME_GRANT_MASK =
1384            FLAG_PERMISSION_USER_SET
1385            | FLAG_PERMISSION_USER_FIXED
1386            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1387
1388    final @Nullable String mRequiredVerifierPackage;
1389    final @NonNull String mRequiredInstallerPackage;
1390    final @NonNull String mRequiredUninstallerPackage;
1391    final @Nullable String mSetupWizardPackage;
1392    final @Nullable String mStorageManagerPackage;
1393    final @NonNull String mServicesSystemSharedLibraryPackageName;
1394    final @NonNull String mSharedSystemSharedLibraryPackageName;
1395
1396    private final PackageUsage mPackageUsage = new PackageUsage();
1397    private final CompilerStats mCompilerStats = new CompilerStats();
1398
1399    class PackageHandler extends Handler {
1400        private boolean mBound = false;
1401        final ArrayList<HandlerParams> mPendingInstalls =
1402            new ArrayList<HandlerParams>();
1403
1404        private boolean connectToService() {
1405            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1406                    " DefaultContainerService");
1407            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1408            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1409            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1410                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1411                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1412                mBound = true;
1413                return true;
1414            }
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416            return false;
1417        }
1418
1419        private void disconnectService() {
1420            mContainerService = null;
1421            mBound = false;
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423            mContext.unbindService(mDefContainerConn);
1424            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425        }
1426
1427        PackageHandler(Looper looper) {
1428            super(looper);
1429        }
1430
1431        public void handleMessage(Message msg) {
1432            try {
1433                doHandleMessage(msg);
1434            } finally {
1435                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1436            }
1437        }
1438
1439        void doHandleMessage(Message msg) {
1440            switch (msg.what) {
1441                case INIT_COPY: {
1442                    HandlerParams params = (HandlerParams) msg.obj;
1443                    int idx = mPendingInstalls.size();
1444                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1445                    // If a bind was already initiated we dont really
1446                    // need to do anything. The pending install
1447                    // will be processed later on.
1448                    if (!mBound) {
1449                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1450                                System.identityHashCode(mHandler));
1451                        // If this is the only one pending we might
1452                        // have to bind to the service again.
1453                        if (!connectToService()) {
1454                            Slog.e(TAG, "Failed to bind to media container service");
1455                            params.serviceError();
1456                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1457                                    System.identityHashCode(mHandler));
1458                            if (params.traceMethod != null) {
1459                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1460                                        params.traceCookie);
1461                            }
1462                            return;
1463                        } else {
1464                            // Once we bind to the service, the first
1465                            // pending request will be processed.
1466                            mPendingInstalls.add(idx, params);
1467                        }
1468                    } else {
1469                        mPendingInstalls.add(idx, params);
1470                        // Already bound to the service. Just make
1471                        // sure we trigger off processing the first request.
1472                        if (idx == 0) {
1473                            mHandler.sendEmptyMessage(MCS_BOUND);
1474                        }
1475                    }
1476                    break;
1477                }
1478                case MCS_BOUND: {
1479                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1480                    if (msg.obj != null) {
1481                        mContainerService = (IMediaContainerService) msg.obj;
1482                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1483                                System.identityHashCode(mHandler));
1484                    }
1485                    if (mContainerService == null) {
1486                        if (!mBound) {
1487                            // Something seriously wrong since we are not bound and we are not
1488                            // waiting for connection. Bail out.
1489                            Slog.e(TAG, "Cannot bind to media container service");
1490                            for (HandlerParams params : mPendingInstalls) {
1491                                // Indicate service bind error
1492                                params.serviceError();
1493                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1494                                        System.identityHashCode(params));
1495                                if (params.traceMethod != null) {
1496                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1497                                            params.traceMethod, params.traceCookie);
1498                                }
1499                                return;
1500                            }
1501                            mPendingInstalls.clear();
1502                        } else {
1503                            Slog.w(TAG, "Waiting to connect to media container service");
1504                        }
1505                    } else if (mPendingInstalls.size() > 0) {
1506                        HandlerParams params = mPendingInstalls.get(0);
1507                        if (params != null) {
1508                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1509                                    System.identityHashCode(params));
1510                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1511                            if (params.startCopy()) {
1512                                // We are done...  look for more work or to
1513                                // go idle.
1514                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1515                                        "Checking for more work or unbind...");
1516                                // Delete pending install
1517                                if (mPendingInstalls.size() > 0) {
1518                                    mPendingInstalls.remove(0);
1519                                }
1520                                if (mPendingInstalls.size() == 0) {
1521                                    if (mBound) {
1522                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1523                                                "Posting delayed MCS_UNBIND");
1524                                        removeMessages(MCS_UNBIND);
1525                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1526                                        // Unbind after a little delay, to avoid
1527                                        // continual thrashing.
1528                                        sendMessageDelayed(ubmsg, 10000);
1529                                    }
1530                                } else {
1531                                    // There are more pending requests in queue.
1532                                    // Just post MCS_BOUND message to trigger processing
1533                                    // of next pending install.
1534                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1535                                            "Posting MCS_BOUND for next work");
1536                                    mHandler.sendEmptyMessage(MCS_BOUND);
1537                                }
1538                            }
1539                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1540                        }
1541                    } else {
1542                        // Should never happen ideally.
1543                        Slog.w(TAG, "Empty queue");
1544                    }
1545                    break;
1546                }
1547                case MCS_RECONNECT: {
1548                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1549                    if (mPendingInstalls.size() > 0) {
1550                        if (mBound) {
1551                            disconnectService();
1552                        }
1553                        if (!connectToService()) {
1554                            Slog.e(TAG, "Failed to bind to media container service");
1555                            for (HandlerParams params : mPendingInstalls) {
1556                                // Indicate service bind error
1557                                params.serviceError();
1558                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1559                                        System.identityHashCode(params));
1560                            }
1561                            mPendingInstalls.clear();
1562                        }
1563                    }
1564                    break;
1565                }
1566                case MCS_UNBIND: {
1567                    // If there is no actual work left, then time to unbind.
1568                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1569
1570                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1571                        if (mBound) {
1572                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1573
1574                            disconnectService();
1575                        }
1576                    } else if (mPendingInstalls.size() > 0) {
1577                        // There are more pending requests in queue.
1578                        // Just post MCS_BOUND message to trigger processing
1579                        // of next pending install.
1580                        mHandler.sendEmptyMessage(MCS_BOUND);
1581                    }
1582
1583                    break;
1584                }
1585                case MCS_GIVE_UP: {
1586                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1587                    HandlerParams params = mPendingInstalls.remove(0);
1588                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1589                            System.identityHashCode(params));
1590                    break;
1591                }
1592                case SEND_PENDING_BROADCAST: {
1593                    String packages[];
1594                    ArrayList<String> components[];
1595                    int size = 0;
1596                    int uids[];
1597                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1598                    synchronized (mPackages) {
1599                        if (mPendingBroadcasts == null) {
1600                            return;
1601                        }
1602                        size = mPendingBroadcasts.size();
1603                        if (size <= 0) {
1604                            // Nothing to be done. Just return
1605                            return;
1606                        }
1607                        packages = new String[size];
1608                        components = new ArrayList[size];
1609                        uids = new int[size];
1610                        int i = 0;  // filling out the above arrays
1611
1612                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1613                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1614                            Iterator<Map.Entry<String, ArrayList<String>>> it
1615                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1616                                            .entrySet().iterator();
1617                            while (it.hasNext() && i < size) {
1618                                Map.Entry<String, ArrayList<String>> ent = it.next();
1619                                packages[i] = ent.getKey();
1620                                components[i] = ent.getValue();
1621                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1622                                uids[i] = (ps != null)
1623                                        ? UserHandle.getUid(packageUserId, ps.appId)
1624                                        : -1;
1625                                i++;
1626                            }
1627                        }
1628                        size = i;
1629                        mPendingBroadcasts.clear();
1630                    }
1631                    // Send broadcasts
1632                    for (int i = 0; i < size; i++) {
1633                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1634                    }
1635                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1636                    break;
1637                }
1638                case START_CLEANING_PACKAGE: {
1639                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1640                    final String packageName = (String)msg.obj;
1641                    final int userId = msg.arg1;
1642                    final boolean andCode = msg.arg2 != 0;
1643                    synchronized (mPackages) {
1644                        if (userId == UserHandle.USER_ALL) {
1645                            int[] users = sUserManager.getUserIds();
1646                            for (int user : users) {
1647                                mSettings.addPackageToCleanLPw(
1648                                        new PackageCleanItem(user, packageName, andCode));
1649                            }
1650                        } else {
1651                            mSettings.addPackageToCleanLPw(
1652                                    new PackageCleanItem(userId, packageName, andCode));
1653                        }
1654                    }
1655                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1656                    startCleaningPackages();
1657                } break;
1658                case POST_INSTALL: {
1659                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1660
1661                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1662                    final boolean didRestore = (msg.arg2 != 0);
1663                    mRunningInstalls.delete(msg.arg1);
1664
1665                    if (data != null) {
1666                        InstallArgs args = data.args;
1667                        PackageInstalledInfo parentRes = data.res;
1668
1669                        final boolean grantPermissions = (args.installFlags
1670                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1671                        final boolean killApp = (args.installFlags
1672                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1673                        final boolean virtualPreload = ((args.installFlags
1674                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1675                        final String[] grantedPermissions = args.installGrantPermissions;
1676
1677                        // Handle the parent package
1678                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1679                                virtualPreload, grantedPermissions, didRestore,
1680                                args.installerPackageName, args.observer);
1681
1682                        // Handle the child packages
1683                        final int childCount = (parentRes.addedChildPackages != null)
1684                                ? parentRes.addedChildPackages.size() : 0;
1685                        for (int i = 0; i < childCount; i++) {
1686                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1687                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1688                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1689                                    args.installerPackageName, args.observer);
1690                        }
1691
1692                        // Log tracing if needed
1693                        if (args.traceMethod != null) {
1694                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1695                                    args.traceCookie);
1696                        }
1697                    } else {
1698                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1699                    }
1700
1701                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1702                } break;
1703                case WRITE_SETTINGS: {
1704                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1705                    synchronized (mPackages) {
1706                        removeMessages(WRITE_SETTINGS);
1707                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1708                        mSettings.writeLPr();
1709                        mDirtyUsers.clear();
1710                    }
1711                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1712                } break;
1713                case WRITE_PACKAGE_RESTRICTIONS: {
1714                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1715                    synchronized (mPackages) {
1716                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1717                        for (int userId : mDirtyUsers) {
1718                            mSettings.writePackageRestrictionsLPr(userId);
1719                        }
1720                        mDirtyUsers.clear();
1721                    }
1722                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1723                } break;
1724                case WRITE_PACKAGE_LIST: {
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1726                    synchronized (mPackages) {
1727                        removeMessages(WRITE_PACKAGE_LIST);
1728                        mSettings.writePackageListLPr(msg.arg1);
1729                    }
1730                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1731                } break;
1732                case CHECK_PENDING_VERIFICATION: {
1733                    final int verificationId = msg.arg1;
1734                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1735
1736                    if ((state != null) && !state.timeoutExtended()) {
1737                        final InstallArgs args = state.getInstallArgs();
1738                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1739
1740                        Slog.i(TAG, "Verification timed out for " + originUri);
1741                        mPendingVerification.remove(verificationId);
1742
1743                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1744
1745                        final UserHandle user = args.getUser();
1746                        if (getDefaultVerificationResponse(user)
1747                                == PackageManager.VERIFICATION_ALLOW) {
1748                            Slog.i(TAG, "Continuing with installation of " + originUri);
1749                            state.setVerifierResponse(Binder.getCallingUid(),
1750                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1751                            broadcastPackageVerified(verificationId, originUri,
1752                                    PackageManager.VERIFICATION_ALLOW, user);
1753                            try {
1754                                ret = args.copyApk(mContainerService, true);
1755                            } catch (RemoteException e) {
1756                                Slog.e(TAG, "Could not contact the ContainerService");
1757                            }
1758                        } else {
1759                            broadcastPackageVerified(verificationId, originUri,
1760                                    PackageManager.VERIFICATION_REJECT, user);
1761                        }
1762
1763                        Trace.asyncTraceEnd(
1764                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1765
1766                        processPendingInstall(args, ret);
1767                        mHandler.sendEmptyMessage(MCS_UNBIND);
1768                    }
1769                    break;
1770                }
1771                case PACKAGE_VERIFIED: {
1772                    final int verificationId = msg.arg1;
1773
1774                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1775                    if (state == null) {
1776                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1777                        break;
1778                    }
1779
1780                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1781
1782                    state.setVerifierResponse(response.callerUid, response.code);
1783
1784                    if (state.isVerificationComplete()) {
1785                        mPendingVerification.remove(verificationId);
1786
1787                        final InstallArgs args = state.getInstallArgs();
1788                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1789
1790                        int ret;
1791                        if (state.isInstallAllowed()) {
1792                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1793                            broadcastPackageVerified(verificationId, originUri,
1794                                    response.code, state.getInstallArgs().getUser());
1795                            try {
1796                                ret = args.copyApk(mContainerService, true);
1797                            } catch (RemoteException e) {
1798                                Slog.e(TAG, "Could not contact the ContainerService");
1799                            }
1800                        } else {
1801                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1802                        }
1803
1804                        Trace.asyncTraceEnd(
1805                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1806
1807                        processPendingInstall(args, ret);
1808                        mHandler.sendEmptyMessage(MCS_UNBIND);
1809                    }
1810
1811                    break;
1812                }
1813                case START_INTENT_FILTER_VERIFICATIONS: {
1814                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1815                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1816                            params.replacing, params.pkg);
1817                    break;
1818                }
1819                case INTENT_FILTER_VERIFIED: {
1820                    final int verificationId = msg.arg1;
1821
1822                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1823                            verificationId);
1824                    if (state == null) {
1825                        Slog.w(TAG, "Invalid IntentFilter verification token "
1826                                + verificationId + " received");
1827                        break;
1828                    }
1829
1830                    final int userId = state.getUserId();
1831
1832                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1833                            "Processing IntentFilter verification with token:"
1834                            + verificationId + " and userId:" + userId);
1835
1836                    final IntentFilterVerificationResponse response =
1837                            (IntentFilterVerificationResponse) msg.obj;
1838
1839                    state.setVerifierResponse(response.callerUid, response.code);
1840
1841                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1842                            "IntentFilter verification with token:" + verificationId
1843                            + " and userId:" + userId
1844                            + " is settings verifier response with response code:"
1845                            + response.code);
1846
1847                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1848                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1849                                + response.getFailedDomainsString());
1850                    }
1851
1852                    if (state.isVerificationComplete()) {
1853                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1854                    } else {
1855                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1856                                "IntentFilter verification with token:" + verificationId
1857                                + " was not said to be complete");
1858                    }
1859
1860                    break;
1861                }
1862                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1863                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1864                            mInstantAppResolverConnection,
1865                            (InstantAppRequest) msg.obj,
1866                            mInstantAppInstallerActivity,
1867                            mHandler);
1868                }
1869            }
1870        }
1871    }
1872
1873    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1874        @Override
1875        public void onGidsChanged(int appId, int userId) {
1876            mHandler.post(new Runnable() {
1877                @Override
1878                public void run() {
1879                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1880                }
1881            });
1882        }
1883        @Override
1884        public void onPermissionGranted(int uid, int userId) {
1885            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1886
1887            // Not critical; if this is lost, the application has to request again.
1888            synchronized (mPackages) {
1889                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1890            }
1891        }
1892        @Override
1893        public void onInstallPermissionGranted() {
1894            synchronized (mPackages) {
1895                scheduleWriteSettingsLocked();
1896            }
1897        }
1898        @Override
1899        public void onPermissionRevoked(int uid, int userId) {
1900            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1901
1902            synchronized (mPackages) {
1903                // Critical; after this call the application should never have the permission
1904                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1905            }
1906
1907            final int appId = UserHandle.getAppId(uid);
1908            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1909        }
1910        @Override
1911        public void onInstallPermissionRevoked() {
1912            synchronized (mPackages) {
1913                scheduleWriteSettingsLocked();
1914            }
1915        }
1916        @Override
1917        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1918            synchronized (mPackages) {
1919                for (int userId : updatedUserIds) {
1920                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1921                }
1922            }
1923        }
1924        @Override
1925        public void onInstallPermissionUpdated() {
1926            synchronized (mPackages) {
1927                scheduleWriteSettingsLocked();
1928            }
1929        }
1930        @Override
1931        public void onPermissionRemoved() {
1932            synchronized (mPackages) {
1933                mSettings.writeLPr();
1934            }
1935        }
1936    };
1937
1938    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1939            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1940            boolean launchedForRestore, String installerPackage,
1941            IPackageInstallObserver2 installObserver) {
1942        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1943            // Send the removed broadcasts
1944            if (res.removedInfo != null) {
1945                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1946            }
1947
1948            // Now that we successfully installed the package, grant runtime
1949            // permissions if requested before broadcasting the install. Also
1950            // for legacy apps in permission review mode we clear the permission
1951            // review flag which is used to emulate runtime permissions for
1952            // legacy apps.
1953            if (grantPermissions) {
1954                final int callingUid = Binder.getCallingUid();
1955                mPermissionManager.grantRequestedRuntimePermissions(
1956                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1957                        mPermissionCallback);
1958            }
1959
1960            final boolean update = res.removedInfo != null
1961                    && res.removedInfo.removedPackage != null;
1962            final String installerPackageName =
1963                    res.installerPackageName != null
1964                            ? res.installerPackageName
1965                            : res.removedInfo != null
1966                                    ? res.removedInfo.installerPackageName
1967                                    : null;
1968
1969            // If this is the first time we have child packages for a disabled privileged
1970            // app that had no children, we grant requested runtime permissions to the new
1971            // children if the parent on the system image had them already granted.
1972            if (res.pkg.parentPackage != null) {
1973                final int callingUid = Binder.getCallingUid();
1974                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1975                        res.pkg, callingUid, mPermissionCallback);
1976            }
1977
1978            synchronized (mPackages) {
1979                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1980            }
1981
1982            final String packageName = res.pkg.applicationInfo.packageName;
1983
1984            // Determine the set of users who are adding this package for
1985            // the first time vs. those who are seeing an update.
1986            int[] firstUserIds = EMPTY_INT_ARRAY;
1987            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1988            int[] updateUserIds = EMPTY_INT_ARRAY;
1989            int[] instantUserIds = EMPTY_INT_ARRAY;
1990            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1991            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1992            for (int newUser : res.newUsers) {
1993                final boolean isInstantApp = ps.getInstantApp(newUser);
1994                if (allNewUsers) {
1995                    if (isInstantApp) {
1996                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1997                    } else {
1998                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
1999                    }
2000                    continue;
2001                }
2002                boolean isNew = true;
2003                for (int origUser : res.origUsers) {
2004                    if (origUser == newUser) {
2005                        isNew = false;
2006                        break;
2007                    }
2008                }
2009                if (isNew) {
2010                    if (isInstantApp) {
2011                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2012                    } else {
2013                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2014                    }
2015                } else {
2016                    if (isInstantApp) {
2017                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2018                    } else {
2019                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2020                    }
2021                }
2022            }
2023
2024            // Send installed broadcasts if the package is not a static shared lib.
2025            if (res.pkg.staticSharedLibName == null) {
2026                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2027
2028                // Send added for users that see the package for the first time
2029                // sendPackageAddedForNewUsers also deals with system apps
2030                int appId = UserHandle.getAppId(res.uid);
2031                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2032                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2033                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2034
2035                // Send added for users that don't see the package for the first time
2036                Bundle extras = new Bundle(1);
2037                extras.putInt(Intent.EXTRA_UID, res.uid);
2038                if (update) {
2039                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2040                }
2041                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2042                        extras, 0 /*flags*/,
2043                        null /*targetPackage*/, null /*finishedReceiver*/,
2044                        updateUserIds, instantUserIds);
2045                if (installerPackageName != null) {
2046                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2047                            extras, 0 /*flags*/,
2048                            installerPackageName, null /*finishedReceiver*/,
2049                            updateUserIds, instantUserIds);
2050                }
2051
2052                // Send replaced for users that don't see the package for the first time
2053                if (update) {
2054                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2055                            packageName, extras, 0 /*flags*/,
2056                            null /*targetPackage*/, null /*finishedReceiver*/,
2057                            updateUserIds, instantUserIds);
2058                    if (installerPackageName != null) {
2059                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2060                                extras, 0 /*flags*/,
2061                                installerPackageName, null /*finishedReceiver*/,
2062                                updateUserIds, instantUserIds);
2063                    }
2064                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2065                            null /*package*/, null /*extras*/, 0 /*flags*/,
2066                            packageName /*targetPackage*/,
2067                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2068                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2069                    // First-install and we did a restore, so we're responsible for the
2070                    // first-launch broadcast.
2071                    if (DEBUG_BACKUP) {
2072                        Slog.i(TAG, "Post-restore of " + packageName
2073                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2074                    }
2075                    sendFirstLaunchBroadcast(packageName, installerPackage,
2076                            firstUserIds, firstInstantUserIds);
2077                }
2078
2079                // Send broadcast package appeared if forward locked/external for all users
2080                // treat asec-hosted packages like removable media on upgrade
2081                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2082                    if (DEBUG_INSTALL) {
2083                        Slog.i(TAG, "upgrading pkg " + res.pkg
2084                                + " is ASEC-hosted -> AVAILABLE");
2085                    }
2086                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2087                    ArrayList<String> pkgList = new ArrayList<>(1);
2088                    pkgList.add(packageName);
2089                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2090                }
2091            }
2092
2093            // Work that needs to happen on first install within each user
2094            if (firstUserIds != null && firstUserIds.length > 0) {
2095                synchronized (mPackages) {
2096                    for (int userId : firstUserIds) {
2097                        // If this app is a browser and it's newly-installed for some
2098                        // users, clear any default-browser state in those users. The
2099                        // app's nature doesn't depend on the user, so we can just check
2100                        // its browser nature in any user and generalize.
2101                        if (packageIsBrowser(packageName, userId)) {
2102                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2103                        }
2104
2105                        // We may also need to apply pending (restored) runtime
2106                        // permission grants within these users.
2107                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2108                    }
2109                }
2110            }
2111
2112            if (allNewUsers && !update) {
2113                notifyPackageAdded(packageName);
2114            }
2115
2116            // Log current value of "unknown sources" setting
2117            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2118                    getUnknownSourcesSettings());
2119
2120            // Remove the replaced package's older resources safely now
2121            // We delete after a gc for applications  on sdcard.
2122            if (res.removedInfo != null && res.removedInfo.args != null) {
2123                Runtime.getRuntime().gc();
2124                synchronized (mInstallLock) {
2125                    res.removedInfo.args.doPostDeleteLI(true);
2126                }
2127            } else {
2128                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2129                // and not block here.
2130                VMRuntime.getRuntime().requestConcurrentGC();
2131            }
2132
2133            // Notify DexManager that the package was installed for new users.
2134            // The updated users should already be indexed and the package code paths
2135            // should not change.
2136            // Don't notify the manager for ephemeral apps as they are not expected to
2137            // survive long enough to benefit of background optimizations.
2138            for (int userId : firstUserIds) {
2139                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2140                // There's a race currently where some install events may interleave with an uninstall.
2141                // This can lead to package info being null (b/36642664).
2142                if (info != null) {
2143                    mDexManager.notifyPackageInstalled(info, userId);
2144                }
2145            }
2146        }
2147
2148        // If someone is watching installs - notify them
2149        if (installObserver != null) {
2150            try {
2151                Bundle extras = extrasForInstallResult(res);
2152                installObserver.onPackageInstalled(res.name, res.returnCode,
2153                        res.returnMsg, extras);
2154            } catch (RemoteException e) {
2155                Slog.i(TAG, "Observer no longer exists.");
2156            }
2157        }
2158    }
2159
2160    private StorageEventListener mStorageListener = new StorageEventListener() {
2161        @Override
2162        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2163            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2164                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2165                    final String volumeUuid = vol.getFsUuid();
2166
2167                    // Clean up any users or apps that were removed or recreated
2168                    // while this volume was missing
2169                    sUserManager.reconcileUsers(volumeUuid);
2170                    reconcileApps(volumeUuid);
2171
2172                    // Clean up any install sessions that expired or were
2173                    // cancelled while this volume was missing
2174                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2175
2176                    loadPrivatePackages(vol);
2177
2178                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2179                    unloadPrivatePackages(vol);
2180                }
2181            }
2182        }
2183
2184        @Override
2185        public void onVolumeForgotten(String fsUuid) {
2186            if (TextUtils.isEmpty(fsUuid)) {
2187                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2188                return;
2189            }
2190
2191            // Remove any apps installed on the forgotten volume
2192            synchronized (mPackages) {
2193                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2194                for (PackageSetting ps : packages) {
2195                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2196                    deletePackageVersioned(new VersionedPackage(ps.name,
2197                            PackageManager.VERSION_CODE_HIGHEST),
2198                            new LegacyPackageDeleteObserver(null).getBinder(),
2199                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2200                    // Try very hard to release any references to this package
2201                    // so we don't risk the system server being killed due to
2202                    // open FDs
2203                    AttributeCache.instance().removePackage(ps.name);
2204                }
2205
2206                mSettings.onVolumeForgotten(fsUuid);
2207                mSettings.writeLPr();
2208            }
2209        }
2210    };
2211
2212    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2213        Bundle extras = null;
2214        switch (res.returnCode) {
2215            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2216                extras = new Bundle();
2217                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2218                        res.origPermission);
2219                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2220                        res.origPackage);
2221                break;
2222            }
2223            case PackageManager.INSTALL_SUCCEEDED: {
2224                extras = new Bundle();
2225                extras.putBoolean(Intent.EXTRA_REPLACING,
2226                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2227                break;
2228            }
2229        }
2230        return extras;
2231    }
2232
2233    void scheduleWriteSettingsLocked() {
2234        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2235            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2236        }
2237    }
2238
2239    void scheduleWritePackageListLocked(int userId) {
2240        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2241            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2242            msg.arg1 = userId;
2243            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2244        }
2245    }
2246
2247    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2248        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2249        scheduleWritePackageRestrictionsLocked(userId);
2250    }
2251
2252    void scheduleWritePackageRestrictionsLocked(int userId) {
2253        final int[] userIds = (userId == UserHandle.USER_ALL)
2254                ? sUserManager.getUserIds() : new int[]{userId};
2255        for (int nextUserId : userIds) {
2256            if (!sUserManager.exists(nextUserId)) return;
2257            mDirtyUsers.add(nextUserId);
2258            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2259                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2260            }
2261        }
2262    }
2263
2264    public static PackageManagerService main(Context context, Installer installer,
2265            boolean factoryTest, boolean onlyCore) {
2266        // Self-check for initial settings.
2267        PackageManagerServiceCompilerMapping.checkProperties();
2268
2269        PackageManagerService m = new PackageManagerService(context, installer,
2270                factoryTest, onlyCore);
2271        m.enableSystemUserPackages();
2272        ServiceManager.addService("package", m);
2273        final PackageManagerNative pmn = m.new PackageManagerNative();
2274        ServiceManager.addService("package_native", pmn);
2275        return m;
2276    }
2277
2278    private void enableSystemUserPackages() {
2279        if (!UserManager.isSplitSystemUser()) {
2280            return;
2281        }
2282        // For system user, enable apps based on the following conditions:
2283        // - app is whitelisted or belong to one of these groups:
2284        //   -- system app which has no launcher icons
2285        //   -- system app which has INTERACT_ACROSS_USERS permission
2286        //   -- system IME app
2287        // - app is not in the blacklist
2288        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2289        Set<String> enableApps = new ArraySet<>();
2290        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2291                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2292                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2293        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2294        enableApps.addAll(wlApps);
2295        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2296                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2297        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2298        enableApps.removeAll(blApps);
2299        Log.i(TAG, "Applications installed for system user: " + enableApps);
2300        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2301                UserHandle.SYSTEM);
2302        final int allAppsSize = allAps.size();
2303        synchronized (mPackages) {
2304            for (int i = 0; i < allAppsSize; i++) {
2305                String pName = allAps.get(i);
2306                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2307                // Should not happen, but we shouldn't be failing if it does
2308                if (pkgSetting == null) {
2309                    continue;
2310                }
2311                boolean install = enableApps.contains(pName);
2312                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2313                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2314                            + " for system user");
2315                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2316                }
2317            }
2318            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2319        }
2320    }
2321
2322    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2323        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2324                Context.DISPLAY_SERVICE);
2325        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2326    }
2327
2328    /**
2329     * Requests that files preopted on a secondary system partition be copied to the data partition
2330     * if possible.  Note that the actual copying of the files is accomplished by init for security
2331     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2332     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2333     */
2334    private static void requestCopyPreoptedFiles() {
2335        final int WAIT_TIME_MS = 100;
2336        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2337        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2338            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2339            // We will wait for up to 100 seconds.
2340            final long timeStart = SystemClock.uptimeMillis();
2341            final long timeEnd = timeStart + 100 * 1000;
2342            long timeNow = timeStart;
2343            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2344                try {
2345                    Thread.sleep(WAIT_TIME_MS);
2346                } catch (InterruptedException e) {
2347                    // Do nothing
2348                }
2349                timeNow = SystemClock.uptimeMillis();
2350                if (timeNow > timeEnd) {
2351                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2352                    Slog.wtf(TAG, "cppreopt did not finish!");
2353                    break;
2354                }
2355            }
2356
2357            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2358        }
2359    }
2360
2361    public PackageManagerService(Context context, Installer installer,
2362            boolean factoryTest, boolean onlyCore) {
2363        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2364        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2365        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2366                SystemClock.uptimeMillis());
2367
2368        if (mSdkVersion <= 0) {
2369            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2370        }
2371
2372        mContext = context;
2373
2374        mFactoryTest = factoryTest;
2375        mOnlyCore = onlyCore;
2376        mMetrics = new DisplayMetrics();
2377        mInstaller = installer;
2378
2379        // Create sub-components that provide services / data. Order here is important.
2380        synchronized (mInstallLock) {
2381        synchronized (mPackages) {
2382            // Expose private service for system components to use.
2383            LocalServices.addService(
2384                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2385            sUserManager = new UserManagerService(context, this,
2386                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2387            mPermissionManager = PermissionManagerService.create(context,
2388                    new DefaultPermissionGrantedCallback() {
2389                        @Override
2390                        public void onDefaultRuntimePermissionsGranted(int userId) {
2391                            synchronized(mPackages) {
2392                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2393                            }
2394                        }
2395                    }, mPackages /*externalLock*/);
2396            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2397            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2398        }
2399        }
2400        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2409                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2410        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2413                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2414
2415        String separateProcesses = SystemProperties.get("debug.separate_processes");
2416        if (separateProcesses != null && separateProcesses.length() > 0) {
2417            if ("*".equals(separateProcesses)) {
2418                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2419                mSeparateProcesses = null;
2420                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2421            } else {
2422                mDefParseFlags = 0;
2423                mSeparateProcesses = separateProcesses.split(",");
2424                Slog.w(TAG, "Running with debug.separate_processes: "
2425                        + separateProcesses);
2426            }
2427        } else {
2428            mDefParseFlags = 0;
2429            mSeparateProcesses = null;
2430        }
2431
2432        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2433                "*dexopt*");
2434        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2435                installer, mInstallLock);
2436        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2437                dexManagerListener);
2438        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2439        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2440
2441        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2442                FgThread.get().getLooper());
2443
2444        getDefaultDisplayMetrics(context, mMetrics);
2445
2446        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2447        SystemConfig systemConfig = SystemConfig.getInstance();
2448        mAvailableFeatures = systemConfig.getAvailableFeatures();
2449        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2450
2451        mProtectedPackages = new ProtectedPackages(mContext);
2452
2453        synchronized (mInstallLock) {
2454        // writer
2455        synchronized (mPackages) {
2456            mHandlerThread = new ServiceThread(TAG,
2457                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2458            mHandlerThread.start();
2459            mHandler = new PackageHandler(mHandlerThread.getLooper());
2460            mProcessLoggingHandler = new ProcessLoggingHandler();
2461            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2462            mInstantAppRegistry = new InstantAppRegistry(this);
2463
2464            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2465            final int builtInLibCount = libConfig.size();
2466            for (int i = 0; i < builtInLibCount; i++) {
2467                String name = libConfig.keyAt(i);
2468                String path = libConfig.valueAt(i);
2469                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2470                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2471            }
2472
2473            SELinuxMMAC.readInstallPolicy();
2474
2475            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2476            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2477            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2478
2479            // Clean up orphaned packages for which the code path doesn't exist
2480            // and they are an update to a system app - caused by bug/32321269
2481            final int packageSettingCount = mSettings.mPackages.size();
2482            for (int i = packageSettingCount - 1; i >= 0; i--) {
2483                PackageSetting ps = mSettings.mPackages.valueAt(i);
2484                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2485                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2486                    mSettings.mPackages.removeAt(i);
2487                    mSettings.enableSystemPackageLPw(ps.name);
2488                }
2489            }
2490
2491            if (mFirstBoot) {
2492                requestCopyPreoptedFiles();
2493            }
2494
2495            String customResolverActivity = Resources.getSystem().getString(
2496                    R.string.config_customResolverActivity);
2497            if (TextUtils.isEmpty(customResolverActivity)) {
2498                customResolverActivity = null;
2499            } else {
2500                mCustomResolverComponentName = ComponentName.unflattenFromString(
2501                        customResolverActivity);
2502            }
2503
2504            long startTime = SystemClock.uptimeMillis();
2505
2506            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2507                    startTime);
2508
2509            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2510            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2511
2512            if (bootClassPath == null) {
2513                Slog.w(TAG, "No BOOTCLASSPATH found!");
2514            }
2515
2516            if (systemServerClassPath == null) {
2517                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2518            }
2519
2520            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2521
2522            final VersionInfo ver = mSettings.getInternalVersion();
2523            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2524            if (mIsUpgrade) {
2525                logCriticalInfo(Log.INFO,
2526                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2527            }
2528
2529            // when upgrading from pre-M, promote system app permissions from install to runtime
2530            mPromoteSystemApps =
2531                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2532
2533            // When upgrading from pre-N, we need to handle package extraction like first boot,
2534            // as there is no profiling data available.
2535            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2536
2537            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2538
2539            // save off the names of pre-existing system packages prior to scanning; we don't
2540            // want to automatically grant runtime permissions for new system apps
2541            if (mPromoteSystemApps) {
2542                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2543                while (pkgSettingIter.hasNext()) {
2544                    PackageSetting ps = pkgSettingIter.next();
2545                    if (isSystemApp(ps)) {
2546                        mExistingSystemPackages.add(ps.name);
2547                    }
2548                }
2549            }
2550
2551            mCacheDir = preparePackageParserCache(mIsUpgrade);
2552
2553            // Set flag to monitor and not change apk file paths when
2554            // scanning install directories.
2555            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2556
2557            if (mIsUpgrade || mFirstBoot) {
2558                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2559            }
2560
2561            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2562            // For security and version matching reason, only consider
2563            // overlay packages if they reside in the right directory.
2564            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2565                    mDefParseFlags
2566                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2567                    scanFlags
2568                    | SCAN_AS_SYSTEM
2569                    | SCAN_AS_VENDOR,
2570                    0);
2571            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2572                    mDefParseFlags
2573                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2574                    scanFlags
2575                    | SCAN_AS_SYSTEM
2576                    | SCAN_AS_PRODUCT,
2577                    0);
2578
2579            mParallelPackageParserCallback.findStaticOverlayPackages();
2580
2581            // Find base frameworks (resource packages without code).
2582            scanDirTracedLI(frameworkDir,
2583                    mDefParseFlags
2584                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2585                    scanFlags
2586                    | SCAN_NO_DEX
2587                    | SCAN_AS_SYSTEM
2588                    | SCAN_AS_PRIVILEGED,
2589                    0);
2590
2591            // Collected privileged system packages.
2592            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2593            scanDirTracedLI(privilegedAppDir,
2594                    mDefParseFlags
2595                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2596                    scanFlags
2597                    | SCAN_AS_SYSTEM
2598                    | SCAN_AS_PRIVILEGED,
2599                    0);
2600
2601            // Collect ordinary system packages.
2602            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2603            scanDirTracedLI(systemAppDir,
2604                    mDefParseFlags
2605                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2606                    scanFlags
2607                    | SCAN_AS_SYSTEM,
2608                    0);
2609
2610            // Collected privileged vendor packages.
2611            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2612            try {
2613                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2614            } catch (IOException e) {
2615                // failed to look up canonical path, continue with original one
2616            }
2617            scanDirTracedLI(privilegedVendorAppDir,
2618                    mDefParseFlags
2619                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2620                    scanFlags
2621                    | SCAN_AS_SYSTEM
2622                    | SCAN_AS_VENDOR
2623                    | SCAN_AS_PRIVILEGED,
2624                    0);
2625
2626            // Collect ordinary vendor packages.
2627            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2628            try {
2629                vendorAppDir = vendorAppDir.getCanonicalFile();
2630            } catch (IOException e) {
2631                // failed to look up canonical path, continue with original one
2632            }
2633            scanDirTracedLI(vendorAppDir,
2634                    mDefParseFlags
2635                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2636                    scanFlags
2637                    | SCAN_AS_SYSTEM
2638                    | SCAN_AS_VENDOR,
2639                    0);
2640
2641            // Collect all OEM packages.
2642            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2643            scanDirTracedLI(oemAppDir,
2644                    mDefParseFlags
2645                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2646                    scanFlags
2647                    | SCAN_AS_SYSTEM
2648                    | SCAN_AS_OEM,
2649                    0);
2650
2651            // Collected privileged product packages.
2652            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2653            try {
2654                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2655            } catch (IOException e) {
2656                // failed to look up canonical path, continue with original one
2657            }
2658            scanDirTracedLI(privilegedProductAppDir,
2659                    mDefParseFlags
2660                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2661                    scanFlags
2662                    | SCAN_AS_SYSTEM
2663                    | SCAN_AS_PRODUCT
2664                    | SCAN_AS_PRIVILEGED,
2665                    0);
2666
2667            // Collect ordinary product packages.
2668            File productAppDir = new File(Environment.getProductDirectory(), "app");
2669            try {
2670                productAppDir = productAppDir.getCanonicalFile();
2671            } catch (IOException e) {
2672                // failed to look up canonical path, continue with original one
2673            }
2674            scanDirTracedLI(productAppDir,
2675                    mDefParseFlags
2676                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2677                    scanFlags
2678                    | SCAN_AS_SYSTEM
2679                    | SCAN_AS_PRODUCT,
2680                    0);
2681
2682            // Prune any system packages that no longer exist.
2683            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2684            // Stub packages must either be replaced with full versions in the /data
2685            // partition or be disabled.
2686            final List<String> stubSystemApps = new ArrayList<>();
2687            if (!mOnlyCore) {
2688                // do this first before mucking with mPackages for the "expecting better" case
2689                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2690                while (pkgIterator.hasNext()) {
2691                    final PackageParser.Package pkg = pkgIterator.next();
2692                    if (pkg.isStub) {
2693                        stubSystemApps.add(pkg.packageName);
2694                    }
2695                }
2696
2697                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2698                while (psit.hasNext()) {
2699                    PackageSetting ps = psit.next();
2700
2701                    /*
2702                     * If this is not a system app, it can't be a
2703                     * disable system app.
2704                     */
2705                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2706                        continue;
2707                    }
2708
2709                    /*
2710                     * If the package is scanned, it's not erased.
2711                     */
2712                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2713                    if (scannedPkg != null) {
2714                        /*
2715                         * If the system app is both scanned and in the
2716                         * disabled packages list, then it must have been
2717                         * added via OTA. Remove it from the currently
2718                         * scanned package so the previously user-installed
2719                         * application can be scanned.
2720                         */
2721                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2722                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2723                                    + ps.name + "; removing system app.  Last known codePath="
2724                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2725                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2726                                    + scannedPkg.getLongVersionCode());
2727                            removePackageLI(scannedPkg, true);
2728                            mExpectingBetter.put(ps.name, ps.codePath);
2729                        }
2730
2731                        continue;
2732                    }
2733
2734                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2735                        psit.remove();
2736                        logCriticalInfo(Log.WARN, "System package " + ps.name
2737                                + " no longer exists; it's data will be wiped");
2738                        // Actual deletion of code and data will be handled by later
2739                        // reconciliation step
2740                    } else {
2741                        // we still have a disabled system package, but, it still might have
2742                        // been removed. check the code path still exists and check there's
2743                        // still a package. the latter can happen if an OTA keeps the same
2744                        // code path, but, changes the package name.
2745                        final PackageSetting disabledPs =
2746                                mSettings.getDisabledSystemPkgLPr(ps.name);
2747                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2748                                || disabledPs.pkg == null) {
2749if (REFACTOR_DEBUG) {
2750Slog.e("TODD",
2751        "Possibly deleted app: " + ps.dumpState_temp()
2752        + "; path: " + (disabledPs.codePath == null ? "<<NULL>>":disabledPs.codePath)
2753        + "; pkg: " + (disabledPs.pkg==null?"<<NULL>>":disabledPs.pkg.toString()));
2754}
2755                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2756                        }
2757                    }
2758                }
2759            }
2760
2761            //look for any incomplete package installations
2762            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2763            for (int i = 0; i < deletePkgsList.size(); i++) {
2764                // Actual deletion of code and data will be handled by later
2765                // reconciliation step
2766                final String packageName = deletePkgsList.get(i).name;
2767                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2768                synchronized (mPackages) {
2769                    mSettings.removePackageLPw(packageName);
2770                }
2771            }
2772
2773            //delete tmp files
2774            deleteTempPackageFiles();
2775
2776            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2777
2778            // Remove any shared userIDs that have no associated packages
2779            mSettings.pruneSharedUsersLPw();
2780            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2781            final int systemPackagesCount = mPackages.size();
2782            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2783                    + " ms, packageCount: " + systemPackagesCount
2784                    + " , timePerPackage: "
2785                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2786                    + " , cached: " + cachedSystemApps);
2787            if (mIsUpgrade && systemPackagesCount > 0) {
2788                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2789                        ((int) systemScanTime) / systemPackagesCount);
2790            }
2791            if (!mOnlyCore) {
2792                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2793                        SystemClock.uptimeMillis());
2794                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2795
2796                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2797                        | PackageParser.PARSE_FORWARD_LOCK,
2798                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2799
2800                // Remove disable package settings for updated system apps that were
2801                // removed via an OTA. If the update is no longer present, remove the
2802                // app completely. Otherwise, revoke their system privileges.
2803                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2804                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2805                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2806if (REFACTOR_DEBUG) {
2807Slog.e("TODD",
2808        "remove update; name: " + deletedAppName + ", exists? " + (deletedPkg != null));
2809}
2810                    final String msg;
2811                    if (deletedPkg == null) {
2812                        // should have found an update, but, we didn't; remove everything
2813                        msg = "Updated system package " + deletedAppName
2814                                + " no longer exists; removing its data";
2815                        // Actual deletion of code and data will be handled by later
2816                        // reconciliation step
2817                    } else {
2818                        // found an update; revoke system privileges
2819                        msg = "Updated system package + " + deletedAppName
2820                                + " no longer exists; revoking system privileges";
2821
2822                        // Don't do anything if a stub is removed from the system image. If
2823                        // we were to remove the uncompressed version from the /data partition,
2824                        // this is where it'd be done.
2825
2826                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2827                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2828                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2829                    }
2830                    logCriticalInfo(Log.WARN, msg);
2831                }
2832
2833                /*
2834                 * Make sure all system apps that we expected to appear on
2835                 * the userdata partition actually showed up. If they never
2836                 * appeared, crawl back and revive the system version.
2837                 */
2838                for (int i = 0; i < mExpectingBetter.size(); i++) {
2839                    final String packageName = mExpectingBetter.keyAt(i);
2840                    if (!mPackages.containsKey(packageName)) {
2841                        final File scanFile = mExpectingBetter.valueAt(i);
2842
2843                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2844                                + " but never showed up; reverting to system");
2845
2846                        final @ParseFlags int reparseFlags;
2847                        final @ScanFlags int rescanFlags;
2848                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2849                            reparseFlags =
2850                                    mDefParseFlags |
2851                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2852                            rescanFlags =
2853                                    scanFlags
2854                                    | SCAN_AS_SYSTEM
2855                                    | SCAN_AS_PRIVILEGED;
2856                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2857                            reparseFlags =
2858                                    mDefParseFlags |
2859                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2860                            rescanFlags =
2861                                    scanFlags
2862                                    | SCAN_AS_SYSTEM;
2863                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2864                            reparseFlags =
2865                                    mDefParseFlags |
2866                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2867                            rescanFlags =
2868                                    scanFlags
2869                                    | SCAN_AS_SYSTEM
2870                                    | SCAN_AS_VENDOR
2871                                    | SCAN_AS_PRIVILEGED;
2872                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2873                            reparseFlags =
2874                                    mDefParseFlags |
2875                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2876                            rescanFlags =
2877                                    scanFlags
2878                                    | SCAN_AS_SYSTEM
2879                                    | SCAN_AS_VENDOR;
2880                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2881                            reparseFlags =
2882                                    mDefParseFlags |
2883                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2884                            rescanFlags =
2885                                    scanFlags
2886                                    | SCAN_AS_SYSTEM
2887                                    | SCAN_AS_OEM;
2888                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2889                            reparseFlags =
2890                                    mDefParseFlags |
2891                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2892                            rescanFlags =
2893                                    scanFlags
2894                                    | SCAN_AS_SYSTEM
2895                                    | SCAN_AS_PRODUCT
2896                                    | SCAN_AS_PRIVILEGED;
2897                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2898                            reparseFlags =
2899                                    mDefParseFlags |
2900                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2901                            rescanFlags =
2902                                    scanFlags
2903                                    | SCAN_AS_SYSTEM
2904                                    | SCAN_AS_PRODUCT;
2905                        } else {
2906                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2907                            continue;
2908                        }
2909
2910                        mSettings.enableSystemPackageLPw(packageName);
2911
2912                        try {
2913                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2914                        } catch (PackageManagerException e) {
2915                            Slog.e(TAG, "Failed to parse original system package: "
2916                                    + e.getMessage());
2917                        }
2918                    }
2919                }
2920
2921                // Uncompress and install any stubbed system applications.
2922                // This must be done last to ensure all stubs are replaced or disabled.
2923                decompressSystemApplications(stubSystemApps, scanFlags);
2924
2925                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2926                                - cachedSystemApps;
2927
2928                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2929                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2930                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2931                        + " ms, packageCount: " + dataPackagesCount
2932                        + " , timePerPackage: "
2933                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2934                        + " , cached: " + cachedNonSystemApps);
2935                if (mIsUpgrade && dataPackagesCount > 0) {
2936                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2937                            ((int) dataScanTime) / dataPackagesCount);
2938                }
2939            }
2940            mExpectingBetter.clear();
2941
2942            // Resolve the storage manager.
2943            mStorageManagerPackage = getStorageManagerPackageName();
2944
2945            // Resolve protected action filters. Only the setup wizard is allowed to
2946            // have a high priority filter for these actions.
2947            mSetupWizardPackage = getSetupWizardPackageName();
2948            if (mProtectedFilters.size() > 0) {
2949                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2950                    Slog.i(TAG, "No setup wizard;"
2951                        + " All protected intents capped to priority 0");
2952                }
2953                for (ActivityIntentInfo filter : mProtectedFilters) {
2954                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2955                        if (DEBUG_FILTERS) {
2956                            Slog.i(TAG, "Found setup wizard;"
2957                                + " allow priority " + filter.getPriority() + ";"
2958                                + " package: " + filter.activity.info.packageName
2959                                + " activity: " + filter.activity.className
2960                                + " priority: " + filter.getPriority());
2961                        }
2962                        // skip setup wizard; allow it to keep the high priority filter
2963                        continue;
2964                    }
2965                    if (DEBUG_FILTERS) {
2966                        Slog.i(TAG, "Protected action; cap priority to 0;"
2967                                + " package: " + filter.activity.info.packageName
2968                                + " activity: " + filter.activity.className
2969                                + " origPrio: " + filter.getPriority());
2970                    }
2971                    filter.setPriority(0);
2972                }
2973            }
2974            mDeferProtectedFilters = false;
2975            mProtectedFilters.clear();
2976
2977            // Now that we know all of the shared libraries, update all clients to have
2978            // the correct library paths.
2979            updateAllSharedLibrariesLPw(null);
2980
2981            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2982                // NOTE: We ignore potential failures here during a system scan (like
2983                // the rest of the commands above) because there's precious little we
2984                // can do about it. A settings error is reported, though.
2985                final List<String> changedAbiCodePath =
2986                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2987                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2988                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
2989                        final String codePathString = changedAbiCodePath.get(i);
2990                        try {
2991                            mInstaller.rmdex(codePathString,
2992                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2993                        } catch (InstallerException ignored) {
2994                        }
2995                    }
2996                }
2997            }
2998
2999            // Now that we know all the packages we are keeping,
3000            // read and update their last usage times.
3001            mPackageUsage.read(mPackages);
3002            mCompilerStats.read();
3003
3004            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3005                    SystemClock.uptimeMillis());
3006            Slog.i(TAG, "Time to scan packages: "
3007                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3008                    + " seconds");
3009
3010            // If the platform SDK has changed since the last time we booted,
3011            // we need to re-grant app permission to catch any new ones that
3012            // appear.  This is really a hack, and means that apps can in some
3013            // cases get permissions that the user didn't initially explicitly
3014            // allow...  it would be nice to have some better way to handle
3015            // this situation.
3016            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3017            if (sdkUpdated) {
3018                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3019                        + mSdkVersion + "; regranting permissions for internal storage");
3020            }
3021            mPermissionManager.updateAllPermissions(
3022                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3023                    mPermissionCallback);
3024            ver.sdkVersion = mSdkVersion;
3025
3026            // If this is the first boot or an update from pre-M, and it is a normal
3027            // boot, then we need to initialize the default preferred apps across
3028            // all defined users.
3029            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3030                for (UserInfo user : sUserManager.getUsers(true)) {
3031                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3032                    applyFactoryDefaultBrowserLPw(user.id);
3033                    primeDomainVerificationsLPw(user.id);
3034                }
3035            }
3036
3037            // Prepare storage for system user really early during boot,
3038            // since core system apps like SettingsProvider and SystemUI
3039            // can't wait for user to start
3040            final int storageFlags;
3041            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3042                storageFlags = StorageManager.FLAG_STORAGE_DE;
3043            } else {
3044                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3045            }
3046            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3047                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3048                    true /* onlyCoreApps */);
3049            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3050                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3051                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3052                traceLog.traceBegin("AppDataFixup");
3053                try {
3054                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3055                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3056                } catch (InstallerException e) {
3057                    Slog.w(TAG, "Trouble fixing GIDs", e);
3058                }
3059                traceLog.traceEnd();
3060
3061                traceLog.traceBegin("AppDataPrepare");
3062                if (deferPackages == null || deferPackages.isEmpty()) {
3063                    return;
3064                }
3065                int count = 0;
3066                for (String pkgName : deferPackages) {
3067                    PackageParser.Package pkg = null;
3068                    synchronized (mPackages) {
3069                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3070                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3071                            pkg = ps.pkg;
3072                        }
3073                    }
3074                    if (pkg != null) {
3075                        synchronized (mInstallLock) {
3076                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3077                                    true /* maybeMigrateAppData */);
3078                        }
3079                        count++;
3080                    }
3081                }
3082                traceLog.traceEnd();
3083                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3084            }, "prepareAppData");
3085
3086            // If this is first boot after an OTA, and a normal boot, then
3087            // we need to clear code cache directories.
3088            // Note that we do *not* clear the application profiles. These remain valid
3089            // across OTAs and are used to drive profile verification (post OTA) and
3090            // profile compilation (without waiting to collect a fresh set of profiles).
3091            if (mIsUpgrade && !onlyCore) {
3092                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3093                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3094                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3095                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3096                        // No apps are running this early, so no need to freeze
3097                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3098                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3099                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3100                    }
3101                }
3102                ver.fingerprint = Build.FINGERPRINT;
3103            }
3104
3105            checkDefaultBrowser();
3106
3107            // clear only after permissions and other defaults have been updated
3108            mExistingSystemPackages.clear();
3109            mPromoteSystemApps = false;
3110
3111            // All the changes are done during package scanning.
3112            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3113
3114            // can downgrade to reader
3115            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3116            mSettings.writeLPr();
3117            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3118            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3119                    SystemClock.uptimeMillis());
3120
3121            if (!mOnlyCore) {
3122                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3123                mRequiredInstallerPackage = getRequiredInstallerLPr();
3124                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3125                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3126                if (mIntentFilterVerifierComponent != null) {
3127                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3128                            mIntentFilterVerifierComponent);
3129                } else {
3130                    mIntentFilterVerifier = null;
3131                }
3132                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3133                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3134                        SharedLibraryInfo.VERSION_UNDEFINED);
3135                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3136                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3137                        SharedLibraryInfo.VERSION_UNDEFINED);
3138            } else {
3139                mRequiredVerifierPackage = null;
3140                mRequiredInstallerPackage = null;
3141                mRequiredUninstallerPackage = null;
3142                mIntentFilterVerifierComponent = null;
3143                mIntentFilterVerifier = null;
3144                mServicesSystemSharedLibraryPackageName = null;
3145                mSharedSystemSharedLibraryPackageName = null;
3146            }
3147
3148            mInstallerService = new PackageInstallerService(context, this);
3149            final Pair<ComponentName, String> instantAppResolverComponent =
3150                    getInstantAppResolverLPr();
3151            if (instantAppResolverComponent != null) {
3152                if (DEBUG_INSTANT) {
3153                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3154                }
3155                mInstantAppResolverConnection = new InstantAppResolverConnection(
3156                        mContext, instantAppResolverComponent.first,
3157                        instantAppResolverComponent.second);
3158                mInstantAppResolverSettingsComponent =
3159                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3160            } else {
3161                mInstantAppResolverConnection = null;
3162                mInstantAppResolverSettingsComponent = null;
3163            }
3164            updateInstantAppInstallerLocked(null);
3165
3166            // Read and update the usage of dex files.
3167            // Do this at the end of PM init so that all the packages have their
3168            // data directory reconciled.
3169            // At this point we know the code paths of the packages, so we can validate
3170            // the disk file and build the internal cache.
3171            // The usage file is expected to be small so loading and verifying it
3172            // should take a fairly small time compare to the other activities (e.g. package
3173            // scanning).
3174            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3175            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3176            for (int userId : currentUserIds) {
3177                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3178            }
3179            mDexManager.load(userPackages);
3180            if (mIsUpgrade) {
3181                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3182                        (int) (SystemClock.uptimeMillis() - startTime));
3183            }
3184        } // synchronized (mPackages)
3185        } // synchronized (mInstallLock)
3186
3187        // Now after opening every single application zip, make sure they
3188        // are all flushed.  Not really needed, but keeps things nice and
3189        // tidy.
3190        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3191        Runtime.getRuntime().gc();
3192        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3193
3194        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3195        FallbackCategoryProvider.loadFallbacks();
3196        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3197
3198        // The initial scanning above does many calls into installd while
3199        // holding the mPackages lock, but we're mostly interested in yelling
3200        // once we have a booted system.
3201        mInstaller.setWarnIfHeld(mPackages);
3202
3203        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3204    }
3205
3206    /**
3207     * Uncompress and install stub applications.
3208     * <p>In order to save space on the system partition, some applications are shipped in a
3209     * compressed form. In addition the compressed bits for the full application, the
3210     * system image contains a tiny stub comprised of only the Android manifest.
3211     * <p>During the first boot, attempt to uncompress and install the full application. If
3212     * the application can't be installed for any reason, disable the stub and prevent
3213     * uncompressing the full application during future boots.
3214     * <p>In order to forcefully attempt an installation of a full application, go to app
3215     * settings and enable the application.
3216     */
3217    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3218        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3219            final String pkgName = stubSystemApps.get(i);
3220            // skip if the system package is already disabled
3221            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3222                stubSystemApps.remove(i);
3223                continue;
3224            }
3225            // skip if the package isn't installed (?!); this should never happen
3226            final PackageParser.Package pkg = mPackages.get(pkgName);
3227            if (pkg == null) {
3228                stubSystemApps.remove(i);
3229                continue;
3230            }
3231            // skip if the package has been disabled by the user
3232            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3233            if (ps != null) {
3234                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3235                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3236                    stubSystemApps.remove(i);
3237                    continue;
3238                }
3239            }
3240
3241            if (DEBUG_COMPRESSION) {
3242                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3243            }
3244
3245            // uncompress the binary to its eventual destination on /data
3246            final File scanFile = decompressPackage(pkg);
3247            if (scanFile == null) {
3248                continue;
3249            }
3250
3251            // install the package to replace the stub on /system
3252            try {
3253                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3254                removePackageLI(pkg, true /*chatty*/);
3255                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3256                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3257                        UserHandle.USER_SYSTEM, "android");
3258                stubSystemApps.remove(i);
3259                continue;
3260            } catch (PackageManagerException e) {
3261                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3262            }
3263
3264            // any failed attempt to install the package will be cleaned up later
3265        }
3266
3267        // disable any stub still left; these failed to install the full application
3268        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3269            final String pkgName = stubSystemApps.get(i);
3270            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3271            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3272                    UserHandle.USER_SYSTEM, "android");
3273            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3274        }
3275    }
3276
3277    /**
3278     * Decompresses the given package on the system image onto
3279     * the /data partition.
3280     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3281     */
3282    private File decompressPackage(PackageParser.Package pkg) {
3283        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3284        if (compressedFiles == null || compressedFiles.length == 0) {
3285            if (DEBUG_COMPRESSION) {
3286                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3287            }
3288            return null;
3289        }
3290        final File dstCodePath =
3291                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3292        int ret = PackageManager.INSTALL_SUCCEEDED;
3293        try {
3294            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3295            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3296            for (File srcFile : compressedFiles) {
3297                final String srcFileName = srcFile.getName();
3298                final String dstFileName = srcFileName.substring(
3299                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3300                final File dstFile = new File(dstCodePath, dstFileName);
3301                ret = decompressFile(srcFile, dstFile);
3302                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3303                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3304                            + "; pkg: " + pkg.packageName
3305                            + ", file: " + dstFileName);
3306                    break;
3307                }
3308            }
3309        } catch (ErrnoException e) {
3310            logCriticalInfo(Log.ERROR, "Failed to decompress"
3311                    + "; pkg: " + pkg.packageName
3312                    + ", err: " + e.errno);
3313        }
3314        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3315            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3316            NativeLibraryHelper.Handle handle = null;
3317            try {
3318                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3319                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3320                        null /*abiOverride*/);
3321            } catch (IOException e) {
3322                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3323                        + "; pkg: " + pkg.packageName);
3324                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3325            } finally {
3326                IoUtils.closeQuietly(handle);
3327            }
3328        }
3329        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3330            if (dstCodePath == null || !dstCodePath.exists()) {
3331                return null;
3332            }
3333            removeCodePathLI(dstCodePath);
3334            return null;
3335        }
3336
3337        return dstCodePath;
3338    }
3339
3340    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3341        // we're only interested in updating the installer appliction when 1) it's not
3342        // already set or 2) the modified package is the installer
3343        if (mInstantAppInstallerActivity != null
3344                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3345                        .equals(modifiedPackage)) {
3346            return;
3347        }
3348        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3349    }
3350
3351    private static File preparePackageParserCache(boolean isUpgrade) {
3352        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3353            return null;
3354        }
3355
3356        // Disable package parsing on eng builds to allow for faster incremental development.
3357        if (Build.IS_ENG) {
3358            return null;
3359        }
3360
3361        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3362            Slog.i(TAG, "Disabling package parser cache due to system property.");
3363            return null;
3364        }
3365
3366        // The base directory for the package parser cache lives under /data/system/.
3367        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3368                "package_cache");
3369        if (cacheBaseDir == null) {
3370            return null;
3371        }
3372
3373        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3374        // This also serves to "GC" unused entries when the package cache version changes (which
3375        // can only happen during upgrades).
3376        if (isUpgrade) {
3377            FileUtils.deleteContents(cacheBaseDir);
3378        }
3379
3380
3381        // Return the versioned package cache directory. This is something like
3382        // "/data/system/package_cache/1"
3383        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3384
3385        // The following is a workaround to aid development on non-numbered userdebug
3386        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3387        // the system partition is newer.
3388        //
3389        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3390        // that starts with "eng." to signify that this is an engineering build and not
3391        // destined for release.
3392        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3393            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3394
3395            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3396            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3397            // in general and should not be used for production changes. In this specific case,
3398            // we know that they will work.
3399            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3400            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3401                FileUtils.deleteContents(cacheBaseDir);
3402                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3403            }
3404        }
3405
3406        return cacheDir;
3407    }
3408
3409    @Override
3410    public boolean isFirstBoot() {
3411        // allow instant applications
3412        return mFirstBoot;
3413    }
3414
3415    @Override
3416    public boolean isOnlyCoreApps() {
3417        // allow instant applications
3418        return mOnlyCore;
3419    }
3420
3421    @Override
3422    public boolean isUpgrade() {
3423        // allow instant applications
3424        // The system property allows testing ota flow when upgraded to the same image.
3425        return mIsUpgrade || SystemProperties.getBoolean(
3426                "persist.pm.mock-upgrade", false /* default */);
3427    }
3428
3429    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3430        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3431
3432        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3433                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3434                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3435        if (matches.size() == 1) {
3436            return matches.get(0).getComponentInfo().packageName;
3437        } else if (matches.size() == 0) {
3438            Log.e(TAG, "There should probably be a verifier, but, none were found");
3439            return null;
3440        }
3441        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3442    }
3443
3444    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3445        synchronized (mPackages) {
3446            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3447            if (libraryEntry == null) {
3448                throw new IllegalStateException("Missing required shared library:" + name);
3449            }
3450            return libraryEntry.apk;
3451        }
3452    }
3453
3454    private @NonNull String getRequiredInstallerLPr() {
3455        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3456        intent.addCategory(Intent.CATEGORY_DEFAULT);
3457        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3458
3459        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3460                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3461                UserHandle.USER_SYSTEM);
3462        if (matches.size() == 1) {
3463            ResolveInfo resolveInfo = matches.get(0);
3464            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3465                throw new RuntimeException("The installer must be a privileged app");
3466            }
3467            return matches.get(0).getComponentInfo().packageName;
3468        } else {
3469            throw new RuntimeException("There must be exactly one installer; found " + matches);
3470        }
3471    }
3472
3473    private @NonNull String getRequiredUninstallerLPr() {
3474        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3475        intent.addCategory(Intent.CATEGORY_DEFAULT);
3476        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3477
3478        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3479                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3480                UserHandle.USER_SYSTEM);
3481        if (resolveInfo == null ||
3482                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3483            throw new RuntimeException("There must be exactly one uninstaller; found "
3484                    + resolveInfo);
3485        }
3486        return resolveInfo.getComponentInfo().packageName;
3487    }
3488
3489    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3490        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3491
3492        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3493                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3494                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3495        ResolveInfo best = null;
3496        final int N = matches.size();
3497        for (int i = 0; i < N; i++) {
3498            final ResolveInfo cur = matches.get(i);
3499            final String packageName = cur.getComponentInfo().packageName;
3500            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3501                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3502                continue;
3503            }
3504
3505            if (best == null || cur.priority > best.priority) {
3506                best = cur;
3507            }
3508        }
3509
3510        if (best != null) {
3511            return best.getComponentInfo().getComponentName();
3512        }
3513        Slog.w(TAG, "Intent filter verifier not found");
3514        return null;
3515    }
3516
3517    @Override
3518    public @Nullable ComponentName getInstantAppResolverComponent() {
3519        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3520            return null;
3521        }
3522        synchronized (mPackages) {
3523            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3524            if (instantAppResolver == null) {
3525                return null;
3526            }
3527            return instantAppResolver.first;
3528        }
3529    }
3530
3531    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3532        final String[] packageArray =
3533                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3534        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3535            if (DEBUG_INSTANT) {
3536                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3537            }
3538            return null;
3539        }
3540
3541        final int callingUid = Binder.getCallingUid();
3542        final int resolveFlags =
3543                MATCH_DIRECT_BOOT_AWARE
3544                | MATCH_DIRECT_BOOT_UNAWARE
3545                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3546        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3547        final Intent resolverIntent = new Intent(actionName);
3548        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3549                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3550        final int N = resolvers.size();
3551        if (N == 0) {
3552            if (DEBUG_INSTANT) {
3553                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3554            }
3555            return null;
3556        }
3557
3558        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3559        for (int i = 0; i < N; i++) {
3560            final ResolveInfo info = resolvers.get(i);
3561
3562            if (info.serviceInfo == null) {
3563                continue;
3564            }
3565
3566            final String packageName = info.serviceInfo.packageName;
3567            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3568                if (DEBUG_INSTANT) {
3569                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3570                            + " pkg: " + packageName + ", info:" + info);
3571                }
3572                continue;
3573            }
3574
3575            if (DEBUG_INSTANT) {
3576                Slog.v(TAG, "Ephemeral resolver found;"
3577                        + " pkg: " + packageName + ", info:" + info);
3578            }
3579            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3580        }
3581        if (DEBUG_INSTANT) {
3582            Slog.v(TAG, "Ephemeral resolver NOT found");
3583        }
3584        return null;
3585    }
3586
3587    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3588        String[] orderedActions = Build.IS_ENG
3589                ? new String[]{
3590                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3591                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3592                : new String[]{
3593                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3594
3595        final int resolveFlags =
3596                MATCH_DIRECT_BOOT_AWARE
3597                        | MATCH_DIRECT_BOOT_UNAWARE
3598                        | Intent.FLAG_IGNORE_EPHEMERAL
3599                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3600        final Intent intent = new Intent();
3601        intent.addCategory(Intent.CATEGORY_DEFAULT);
3602        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3603        List<ResolveInfo> matches = null;
3604        for (String action : orderedActions) {
3605            intent.setAction(action);
3606            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3607                    resolveFlags, UserHandle.USER_SYSTEM);
3608            if (matches.isEmpty()) {
3609                if (DEBUG_INSTANT) {
3610                    Slog.d(TAG, "Instant App installer not found with " + action);
3611                }
3612            } else {
3613                break;
3614            }
3615        }
3616        Iterator<ResolveInfo> iter = matches.iterator();
3617        while (iter.hasNext()) {
3618            final ResolveInfo rInfo = iter.next();
3619            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3620            if (ps != null) {
3621                final PermissionsState permissionsState = ps.getPermissionsState();
3622                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3623                        || Build.IS_ENG) {
3624                    continue;
3625                }
3626            }
3627            iter.remove();
3628        }
3629        if (matches.size() == 0) {
3630            return null;
3631        } else if (matches.size() == 1) {
3632            return (ActivityInfo) matches.get(0).getComponentInfo();
3633        } else {
3634            throw new RuntimeException(
3635                    "There must be at most one ephemeral installer; found " + matches);
3636        }
3637    }
3638
3639    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3640            @NonNull ComponentName resolver) {
3641        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3642                .addCategory(Intent.CATEGORY_DEFAULT)
3643                .setPackage(resolver.getPackageName());
3644        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3645        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3646                UserHandle.USER_SYSTEM);
3647        if (matches.isEmpty()) {
3648            return null;
3649        }
3650        return matches.get(0).getComponentInfo().getComponentName();
3651    }
3652
3653    private void primeDomainVerificationsLPw(int userId) {
3654        if (DEBUG_DOMAIN_VERIFICATION) {
3655            Slog.d(TAG, "Priming domain verifications in user " + userId);
3656        }
3657
3658        SystemConfig systemConfig = SystemConfig.getInstance();
3659        ArraySet<String> packages = systemConfig.getLinkedApps();
3660
3661        for (String packageName : packages) {
3662            PackageParser.Package pkg = mPackages.get(packageName);
3663            if (pkg != null) {
3664                if (!pkg.isSystem()) {
3665                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3666                    continue;
3667                }
3668
3669                ArraySet<String> domains = null;
3670                for (PackageParser.Activity a : pkg.activities) {
3671                    for (ActivityIntentInfo filter : a.intents) {
3672                        if (hasValidDomains(filter)) {
3673                            if (domains == null) {
3674                                domains = new ArraySet<String>();
3675                            }
3676                            domains.addAll(filter.getHostsList());
3677                        }
3678                    }
3679                }
3680
3681                if (domains != null && domains.size() > 0) {
3682                    if (DEBUG_DOMAIN_VERIFICATION) {
3683                        Slog.v(TAG, "      + " + packageName);
3684                    }
3685                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3686                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3687                    // and then 'always' in the per-user state actually used for intent resolution.
3688                    final IntentFilterVerificationInfo ivi;
3689                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3690                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3691                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3692                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3693                } else {
3694                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3695                            + "' does not handle web links");
3696                }
3697            } else {
3698                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3699            }
3700        }
3701
3702        scheduleWritePackageRestrictionsLocked(userId);
3703        scheduleWriteSettingsLocked();
3704    }
3705
3706    private void applyFactoryDefaultBrowserLPw(int userId) {
3707        // The default browser app's package name is stored in a string resource,
3708        // with a product-specific overlay used for vendor customization.
3709        String browserPkg = mContext.getResources().getString(
3710                com.android.internal.R.string.default_browser);
3711        if (!TextUtils.isEmpty(browserPkg)) {
3712            // non-empty string => required to be a known package
3713            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3714            if (ps == null) {
3715                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3716                browserPkg = null;
3717            } else {
3718                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3719            }
3720        }
3721
3722        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3723        // default.  If there's more than one, just leave everything alone.
3724        if (browserPkg == null) {
3725            calculateDefaultBrowserLPw(userId);
3726        }
3727    }
3728
3729    private void calculateDefaultBrowserLPw(int userId) {
3730        List<String> allBrowsers = resolveAllBrowserApps(userId);
3731        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3732        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3733    }
3734
3735    private List<String> resolveAllBrowserApps(int userId) {
3736        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3737        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3738                PackageManager.MATCH_ALL, userId);
3739
3740        final int count = list.size();
3741        List<String> result = new ArrayList<String>(count);
3742        for (int i=0; i<count; i++) {
3743            ResolveInfo info = list.get(i);
3744            if (info.activityInfo == null
3745                    || !info.handleAllWebDataURI
3746                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3747                    || result.contains(info.activityInfo.packageName)) {
3748                continue;
3749            }
3750            result.add(info.activityInfo.packageName);
3751        }
3752
3753        return result;
3754    }
3755
3756    private boolean packageIsBrowser(String packageName, int userId) {
3757        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3758                PackageManager.MATCH_ALL, userId);
3759        final int N = list.size();
3760        for (int i = 0; i < N; i++) {
3761            ResolveInfo info = list.get(i);
3762            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3763                return true;
3764            }
3765        }
3766        return false;
3767    }
3768
3769    private void checkDefaultBrowser() {
3770        final int myUserId = UserHandle.myUserId();
3771        final String packageName = getDefaultBrowserPackageName(myUserId);
3772        if (packageName != null) {
3773            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3774            if (info == null) {
3775                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3776                synchronized (mPackages) {
3777                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3778                }
3779            }
3780        }
3781    }
3782
3783    @Override
3784    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3785            throws RemoteException {
3786        try {
3787            return super.onTransact(code, data, reply, flags);
3788        } catch (RuntimeException e) {
3789            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3790                Slog.wtf(TAG, "Package Manager Crash", e);
3791            }
3792            throw e;
3793        }
3794    }
3795
3796    static int[] appendInts(int[] cur, int[] add) {
3797        if (add == null) return cur;
3798        if (cur == null) return add;
3799        final int N = add.length;
3800        for (int i=0; i<N; i++) {
3801            cur = appendInt(cur, add[i]);
3802        }
3803        return cur;
3804    }
3805
3806    /**
3807     * Returns whether or not a full application can see an instant application.
3808     * <p>
3809     * Currently, there are three cases in which this can occur:
3810     * <ol>
3811     * <li>The calling application is a "special" process. Special processes
3812     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3813     * <li>The calling application has the permission
3814     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3815     * <li>The calling application is the default launcher on the
3816     *     system partition.</li>
3817     * </ol>
3818     */
3819    private boolean canViewInstantApps(int callingUid, int userId) {
3820        if (callingUid < Process.FIRST_APPLICATION_UID) {
3821            return true;
3822        }
3823        if (mContext.checkCallingOrSelfPermission(
3824                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3825            return true;
3826        }
3827        if (mContext.checkCallingOrSelfPermission(
3828                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3829            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3830            if (homeComponent != null
3831                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3832                return true;
3833            }
3834        }
3835        return false;
3836    }
3837
3838    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3839        if (!sUserManager.exists(userId)) return null;
3840        if (ps == null) {
3841            return null;
3842        }
3843        PackageParser.Package p = ps.pkg;
3844        if (p == null) {
3845            return null;
3846        }
3847        final int callingUid = Binder.getCallingUid();
3848        // Filter out ephemeral app metadata:
3849        //   * The system/shell/root can see metadata for any app
3850        //   * An installed app can see metadata for 1) other installed apps
3851        //     and 2) ephemeral apps that have explicitly interacted with it
3852        //   * Ephemeral apps can only see their own data and exposed installed apps
3853        //   * Holding a signature permission allows seeing instant apps
3854        if (filterAppAccessLPr(ps, callingUid, userId)) {
3855            return null;
3856        }
3857
3858        final PermissionsState permissionsState = ps.getPermissionsState();
3859
3860        // Compute GIDs only if requested
3861        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3862                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3863        // Compute granted permissions only if package has requested permissions
3864        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3865                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3866        final PackageUserState state = ps.readUserState(userId);
3867
3868        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3869                && ps.isSystem()) {
3870            flags |= MATCH_ANY_USER;
3871        }
3872
3873        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3874                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3875
3876        if (packageInfo == null) {
3877            return null;
3878        }
3879
3880        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3881                resolveExternalPackageNameLPr(p);
3882
3883        return packageInfo;
3884    }
3885
3886    @Override
3887    public void checkPackageStartable(String packageName, int userId) {
3888        final int callingUid = Binder.getCallingUid();
3889        if (getInstantAppPackageName(callingUid) != null) {
3890            throw new SecurityException("Instant applications don't have access to this method");
3891        }
3892        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3893        synchronized (mPackages) {
3894            final PackageSetting ps = mSettings.mPackages.get(packageName);
3895            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3896                throw new SecurityException("Package " + packageName + " was not found!");
3897            }
3898
3899            if (!ps.getInstalled(userId)) {
3900                throw new SecurityException(
3901                        "Package " + packageName + " was not installed for user " + userId + "!");
3902            }
3903
3904            if (mSafeMode && !ps.isSystem()) {
3905                throw new SecurityException("Package " + packageName + " not a system app!");
3906            }
3907
3908            if (mFrozenPackages.contains(packageName)) {
3909                throw new SecurityException("Package " + packageName + " is currently frozen!");
3910            }
3911
3912            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3913                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3914            }
3915        }
3916    }
3917
3918    @Override
3919    public boolean isPackageAvailable(String packageName, int userId) {
3920        if (!sUserManager.exists(userId)) return false;
3921        final int callingUid = Binder.getCallingUid();
3922        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3923                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3924        synchronized (mPackages) {
3925            PackageParser.Package p = mPackages.get(packageName);
3926            if (p != null) {
3927                final PackageSetting ps = (PackageSetting) p.mExtras;
3928                if (filterAppAccessLPr(ps, callingUid, userId)) {
3929                    return false;
3930                }
3931                if (ps != null) {
3932                    final PackageUserState state = ps.readUserState(userId);
3933                    if (state != null) {
3934                        return PackageParser.isAvailable(state);
3935                    }
3936                }
3937            }
3938        }
3939        return false;
3940    }
3941
3942    @Override
3943    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3944        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3945                flags, Binder.getCallingUid(), userId);
3946    }
3947
3948    @Override
3949    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3950            int flags, int userId) {
3951        return getPackageInfoInternal(versionedPackage.getPackageName(),
3952                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3953    }
3954
3955    /**
3956     * Important: The provided filterCallingUid is used exclusively to filter out packages
3957     * that can be seen based on user state. It's typically the original caller uid prior
3958     * to clearing. Because it can only be provided by trusted code, it's value can be
3959     * trusted and will be used as-is; unlike userId which will be validated by this method.
3960     */
3961    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3962            int flags, int filterCallingUid, int userId) {
3963        if (!sUserManager.exists(userId)) return null;
3964        flags = updateFlagsForPackage(flags, userId, packageName);
3965        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3966                false /* requireFullPermission */, false /* checkShell */, "get package info");
3967
3968        // reader
3969        synchronized (mPackages) {
3970            // Normalize package name to handle renamed packages and static libs
3971            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3972
3973            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3974            if (matchFactoryOnly) {
3975                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3976                if (ps != null) {
3977                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3978                        return null;
3979                    }
3980                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3981                        return null;
3982                    }
3983                    return generatePackageInfo(ps, flags, userId);
3984                }
3985            }
3986
3987            PackageParser.Package p = mPackages.get(packageName);
3988            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3989                return null;
3990            }
3991            if (DEBUG_PACKAGE_INFO)
3992                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3993            if (p != null) {
3994                final PackageSetting ps = (PackageSetting) p.mExtras;
3995                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3996                    return null;
3997                }
3998                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3999                    return null;
4000                }
4001                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4002            }
4003            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4004                final PackageSetting ps = mSettings.mPackages.get(packageName);
4005                if (ps == null) return null;
4006                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4007                    return null;
4008                }
4009                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4010                    return null;
4011                }
4012                return generatePackageInfo(ps, flags, userId);
4013            }
4014        }
4015        return null;
4016    }
4017
4018    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4019        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4020            return true;
4021        }
4022        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4023            return true;
4024        }
4025        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4026            return true;
4027        }
4028        return false;
4029    }
4030
4031    private boolean isComponentVisibleToInstantApp(
4032            @Nullable ComponentName component, @ComponentType int type) {
4033        if (type == TYPE_ACTIVITY) {
4034            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4035            return activity != null
4036                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4037                    : false;
4038        } else if (type == TYPE_RECEIVER) {
4039            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4040            return activity != null
4041                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4042                    : false;
4043        } else if (type == TYPE_SERVICE) {
4044            final PackageParser.Service service = mServices.mServices.get(component);
4045            return service != null
4046                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4047                    : false;
4048        } else if (type == TYPE_PROVIDER) {
4049            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4050            return provider != null
4051                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4052                    : false;
4053        } else if (type == TYPE_UNKNOWN) {
4054            return isComponentVisibleToInstantApp(component);
4055        }
4056        return false;
4057    }
4058
4059    /**
4060     * Returns whether or not access to the application should be filtered.
4061     * <p>
4062     * Access may be limited based upon whether the calling or target applications
4063     * are instant applications.
4064     *
4065     * @see #canAccessInstantApps(int)
4066     */
4067    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4068            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4069        // if we're in an isolated process, get the real calling UID
4070        if (Process.isIsolated(callingUid)) {
4071            callingUid = mIsolatedOwners.get(callingUid);
4072        }
4073        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4074        final boolean callerIsInstantApp = instantAppPkgName != null;
4075        if (ps == null) {
4076            if (callerIsInstantApp) {
4077                // pretend the application exists, but, needs to be filtered
4078                return true;
4079            }
4080            return false;
4081        }
4082        // if the target and caller are the same application, don't filter
4083        if (isCallerSameApp(ps.name, callingUid)) {
4084            return false;
4085        }
4086        if (callerIsInstantApp) {
4087            // request for a specific component; if it hasn't been explicitly exposed, filter
4088            if (component != null) {
4089                return !isComponentVisibleToInstantApp(component, componentType);
4090            }
4091            // request for application; if no components have been explicitly exposed, filter
4092            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4093        }
4094        if (ps.getInstantApp(userId)) {
4095            // caller can see all components of all instant applications, don't filter
4096            if (canViewInstantApps(callingUid, userId)) {
4097                return false;
4098            }
4099            // request for a specific instant application component, filter
4100            if (component != null) {
4101                return true;
4102            }
4103            // request for an instant application; if the caller hasn't been granted access, filter
4104            return !mInstantAppRegistry.isInstantAccessGranted(
4105                    userId, UserHandle.getAppId(callingUid), ps.appId);
4106        }
4107        return false;
4108    }
4109
4110    /**
4111     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4112     */
4113    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4114        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4115    }
4116
4117    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4118            int flags) {
4119        // Callers can access only the libs they depend on, otherwise they need to explicitly
4120        // ask for the shared libraries given the caller is allowed to access all static libs.
4121        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4122            // System/shell/root get to see all static libs
4123            final int appId = UserHandle.getAppId(uid);
4124            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4125                    || appId == Process.ROOT_UID) {
4126                return false;
4127            }
4128        }
4129
4130        // No package means no static lib as it is always on internal storage
4131        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4132            return false;
4133        }
4134
4135        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4136                ps.pkg.staticSharedLibVersion);
4137        if (libEntry == null) {
4138            return false;
4139        }
4140
4141        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4142        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4143        if (uidPackageNames == null) {
4144            return true;
4145        }
4146
4147        for (String uidPackageName : uidPackageNames) {
4148            if (ps.name.equals(uidPackageName)) {
4149                return false;
4150            }
4151            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4152            if (uidPs != null) {
4153                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4154                        libEntry.info.getName());
4155                if (index < 0) {
4156                    continue;
4157                }
4158                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4159                    return false;
4160                }
4161            }
4162        }
4163        return true;
4164    }
4165
4166    @Override
4167    public String[] currentToCanonicalPackageNames(String[] names) {
4168        final int callingUid = Binder.getCallingUid();
4169        if (getInstantAppPackageName(callingUid) != null) {
4170            return names;
4171        }
4172        final String[] out = new String[names.length];
4173        // reader
4174        synchronized (mPackages) {
4175            final int callingUserId = UserHandle.getUserId(callingUid);
4176            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4177            for (int i=names.length-1; i>=0; i--) {
4178                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4179                boolean translateName = false;
4180                if (ps != null && ps.realName != null) {
4181                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4182                    translateName = !targetIsInstantApp
4183                            || canViewInstantApps
4184                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4185                                    UserHandle.getAppId(callingUid), ps.appId);
4186                }
4187                out[i] = translateName ? ps.realName : names[i];
4188            }
4189        }
4190        return out;
4191    }
4192
4193    @Override
4194    public String[] canonicalToCurrentPackageNames(String[] names) {
4195        final int callingUid = Binder.getCallingUid();
4196        if (getInstantAppPackageName(callingUid) != null) {
4197            return names;
4198        }
4199        final String[] out = new String[names.length];
4200        // reader
4201        synchronized (mPackages) {
4202            final int callingUserId = UserHandle.getUserId(callingUid);
4203            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4204            for (int i=names.length-1; i>=0; i--) {
4205                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4206                boolean translateName = false;
4207                if (cur != null) {
4208                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4209                    final boolean targetIsInstantApp =
4210                            ps != null && ps.getInstantApp(callingUserId);
4211                    translateName = !targetIsInstantApp
4212                            || canViewInstantApps
4213                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4214                                    UserHandle.getAppId(callingUid), ps.appId);
4215                }
4216                out[i] = translateName ? cur : names[i];
4217            }
4218        }
4219        return out;
4220    }
4221
4222    @Override
4223    public int getPackageUid(String packageName, int flags, int userId) {
4224        if (!sUserManager.exists(userId)) return -1;
4225        final int callingUid = Binder.getCallingUid();
4226        flags = updateFlagsForPackage(flags, userId, packageName);
4227        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4228                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4229
4230        // reader
4231        synchronized (mPackages) {
4232            final PackageParser.Package p = mPackages.get(packageName);
4233            if (p != null && p.isMatch(flags)) {
4234                PackageSetting ps = (PackageSetting) p.mExtras;
4235                if (filterAppAccessLPr(ps, callingUid, userId)) {
4236                    return -1;
4237                }
4238                return UserHandle.getUid(userId, p.applicationInfo.uid);
4239            }
4240            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4241                final PackageSetting ps = mSettings.mPackages.get(packageName);
4242                if (ps != null && ps.isMatch(flags)
4243                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4244                    return UserHandle.getUid(userId, ps.appId);
4245                }
4246            }
4247        }
4248
4249        return -1;
4250    }
4251
4252    @Override
4253    public int[] getPackageGids(String packageName, int flags, int userId) {
4254        if (!sUserManager.exists(userId)) return null;
4255        final int callingUid = Binder.getCallingUid();
4256        flags = updateFlagsForPackage(flags, userId, packageName);
4257        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4258                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4259
4260        // reader
4261        synchronized (mPackages) {
4262            final PackageParser.Package p = mPackages.get(packageName);
4263            if (p != null && p.isMatch(flags)) {
4264                PackageSetting ps = (PackageSetting) p.mExtras;
4265                if (filterAppAccessLPr(ps, callingUid, userId)) {
4266                    return null;
4267                }
4268                // TODO: Shouldn't this be checking for package installed state for userId and
4269                // return null?
4270                return ps.getPermissionsState().computeGids(userId);
4271            }
4272            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4273                final PackageSetting ps = mSettings.mPackages.get(packageName);
4274                if (ps != null && ps.isMatch(flags)
4275                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4276                    return ps.getPermissionsState().computeGids(userId);
4277                }
4278            }
4279        }
4280
4281        return null;
4282    }
4283
4284    @Override
4285    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4286        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4287    }
4288
4289    @Override
4290    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4291            int flags) {
4292        final List<PermissionInfo> permissionList =
4293                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4294        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4295    }
4296
4297    @Override
4298    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4299        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4300    }
4301
4302    @Override
4303    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4304        final List<PermissionGroupInfo> permissionList =
4305                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4306        return (permissionList == null)
4307                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4308    }
4309
4310    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4311            int filterCallingUid, int userId) {
4312        if (!sUserManager.exists(userId)) return null;
4313        PackageSetting ps = mSettings.mPackages.get(packageName);
4314        if (ps != null) {
4315            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4316                return null;
4317            }
4318            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4319                return null;
4320            }
4321            if (ps.pkg == null) {
4322                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4323                if (pInfo != null) {
4324                    return pInfo.applicationInfo;
4325                }
4326                return null;
4327            }
4328            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4329                    ps.readUserState(userId), userId);
4330            if (ai != null) {
4331                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4332            }
4333            return ai;
4334        }
4335        return null;
4336    }
4337
4338    @Override
4339    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4340        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4341    }
4342
4343    /**
4344     * Important: The provided filterCallingUid is used exclusively to filter out applications
4345     * that can be seen based on user state. It's typically the original caller uid prior
4346     * to clearing. Because it can only be provided by trusted code, it's value can be
4347     * trusted and will be used as-is; unlike userId which will be validated by this method.
4348     */
4349    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4350            int filterCallingUid, int userId) {
4351        if (!sUserManager.exists(userId)) return null;
4352        flags = updateFlagsForApplication(flags, userId, packageName);
4353        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4354                false /* requireFullPermission */, false /* checkShell */, "get application info");
4355
4356        // writer
4357        synchronized (mPackages) {
4358            // Normalize package name to handle renamed packages and static libs
4359            packageName = resolveInternalPackageNameLPr(packageName,
4360                    PackageManager.VERSION_CODE_HIGHEST);
4361
4362            PackageParser.Package p = mPackages.get(packageName);
4363            if (DEBUG_PACKAGE_INFO) Log.v(
4364                    TAG, "getApplicationInfo " + packageName
4365                    + ": " + p);
4366            if (p != null) {
4367                PackageSetting ps = mSettings.mPackages.get(packageName);
4368                if (ps == null) return null;
4369                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4370                    return null;
4371                }
4372                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4373                    return null;
4374                }
4375                // Note: isEnabledLP() does not apply here - always return info
4376                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4377                        p, flags, ps.readUserState(userId), userId);
4378                if (ai != null) {
4379                    ai.packageName = resolveExternalPackageNameLPr(p);
4380                }
4381                return ai;
4382            }
4383            if ("android".equals(packageName)||"system".equals(packageName)) {
4384                return mAndroidApplication;
4385            }
4386            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4387                // Already generates the external package name
4388                return generateApplicationInfoFromSettingsLPw(packageName,
4389                        flags, filterCallingUid, userId);
4390            }
4391        }
4392        return null;
4393    }
4394
4395    private String normalizePackageNameLPr(String packageName) {
4396        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4397        return normalizedPackageName != null ? normalizedPackageName : packageName;
4398    }
4399
4400    @Override
4401    public void deletePreloadsFileCache() {
4402        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4403            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4404        }
4405        File dir = Environment.getDataPreloadsFileCacheDirectory();
4406        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4407        FileUtils.deleteContents(dir);
4408    }
4409
4410    @Override
4411    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4412            final int storageFlags, final IPackageDataObserver observer) {
4413        mContext.enforceCallingOrSelfPermission(
4414                android.Manifest.permission.CLEAR_APP_CACHE, null);
4415        mHandler.post(() -> {
4416            boolean success = false;
4417            try {
4418                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4419                success = true;
4420            } catch (IOException e) {
4421                Slog.w(TAG, e);
4422            }
4423            if (observer != null) {
4424                try {
4425                    observer.onRemoveCompleted(null, success);
4426                } catch (RemoteException e) {
4427                    Slog.w(TAG, e);
4428                }
4429            }
4430        });
4431    }
4432
4433    @Override
4434    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4435            final int storageFlags, final IntentSender pi) {
4436        mContext.enforceCallingOrSelfPermission(
4437                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4438        mHandler.post(() -> {
4439            boolean success = false;
4440            try {
4441                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4442                success = true;
4443            } catch (IOException e) {
4444                Slog.w(TAG, e);
4445            }
4446            if (pi != null) {
4447                try {
4448                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4449                } catch (SendIntentException e) {
4450                    Slog.w(TAG, e);
4451                }
4452            }
4453        });
4454    }
4455
4456    /**
4457     * Blocking call to clear various types of cached data across the system
4458     * until the requested bytes are available.
4459     */
4460    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4461        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4462        final File file = storage.findPathForUuid(volumeUuid);
4463        if (file.getUsableSpace() >= bytes) return;
4464
4465        if (ENABLE_FREE_CACHE_V2) {
4466            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4467                    volumeUuid);
4468            final boolean aggressive = (storageFlags
4469                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4470            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4471
4472            // 1. Pre-flight to determine if we have any chance to succeed
4473            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4474            if (internalVolume && (aggressive || SystemProperties
4475                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4476                deletePreloadsFileCache();
4477                if (file.getUsableSpace() >= bytes) return;
4478            }
4479
4480            // 3. Consider parsed APK data (aggressive only)
4481            if (internalVolume && aggressive) {
4482                FileUtils.deleteContents(mCacheDir);
4483                if (file.getUsableSpace() >= bytes) return;
4484            }
4485
4486            // 4. Consider cached app data (above quotas)
4487            try {
4488                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4489                        Installer.FLAG_FREE_CACHE_V2);
4490            } catch (InstallerException ignored) {
4491            }
4492            if (file.getUsableSpace() >= bytes) return;
4493
4494            // 5. Consider shared libraries with refcount=0 and age>min cache period
4495            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4496                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4497                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4498                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4499                return;
4500            }
4501
4502            // 6. Consider dexopt output (aggressive only)
4503            // TODO: Implement
4504
4505            // 7. Consider installed instant apps unused longer than min cache period
4506            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4507                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4508                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4509                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4510                return;
4511            }
4512
4513            // 8. Consider cached app data (below quotas)
4514            try {
4515                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4516                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4517            } catch (InstallerException ignored) {
4518            }
4519            if (file.getUsableSpace() >= bytes) return;
4520
4521            // 9. Consider DropBox entries
4522            // TODO: Implement
4523
4524            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4525            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4526                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4527                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4528                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4529                return;
4530            }
4531        } else {
4532            try {
4533                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4534            } catch (InstallerException ignored) {
4535            }
4536            if (file.getUsableSpace() >= bytes) return;
4537        }
4538
4539        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4540    }
4541
4542    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4543            throws IOException {
4544        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4545        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4546
4547        List<VersionedPackage> packagesToDelete = null;
4548        final long now = System.currentTimeMillis();
4549
4550        synchronized (mPackages) {
4551            final int[] allUsers = sUserManager.getUserIds();
4552            final int libCount = mSharedLibraries.size();
4553            for (int i = 0; i < libCount; i++) {
4554                final LongSparseArray<SharedLibraryEntry> versionedLib
4555                        = mSharedLibraries.valueAt(i);
4556                if (versionedLib == null) {
4557                    continue;
4558                }
4559                final int versionCount = versionedLib.size();
4560                for (int j = 0; j < versionCount; j++) {
4561                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4562                    // Skip packages that are not static shared libs.
4563                    if (!libInfo.isStatic()) {
4564                        break;
4565                    }
4566                    // Important: We skip static shared libs used for some user since
4567                    // in such a case we need to keep the APK on the device. The check for
4568                    // a lib being used for any user is performed by the uninstall call.
4569                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4570                    // Resolve the package name - we use synthetic package names internally
4571                    final String internalPackageName = resolveInternalPackageNameLPr(
4572                            declaringPackage.getPackageName(),
4573                            declaringPackage.getLongVersionCode());
4574                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4575                    // Skip unused static shared libs cached less than the min period
4576                    // to prevent pruning a lib needed by a subsequently installed package.
4577                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4578                        continue;
4579                    }
4580                    if (packagesToDelete == null) {
4581                        packagesToDelete = new ArrayList<>();
4582                    }
4583                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4584                            declaringPackage.getLongVersionCode()));
4585                }
4586            }
4587        }
4588
4589        if (packagesToDelete != null) {
4590            final int packageCount = packagesToDelete.size();
4591            for (int i = 0; i < packageCount; i++) {
4592                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4593                // Delete the package synchronously (will fail of the lib used for any user).
4594                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4595                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4596                                == PackageManager.DELETE_SUCCEEDED) {
4597                    if (volume.getUsableSpace() >= neededSpace) {
4598                        return true;
4599                    }
4600                }
4601            }
4602        }
4603
4604        return false;
4605    }
4606
4607    /**
4608     * Update given flags based on encryption status of current user.
4609     */
4610    private int updateFlags(int flags, int userId) {
4611        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4612                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4613            // Caller expressed an explicit opinion about what encryption
4614            // aware/unaware components they want to see, so fall through and
4615            // give them what they want
4616        } else {
4617            // Caller expressed no opinion, so match based on user state
4618            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4619                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4620            } else {
4621                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4622            }
4623        }
4624        return flags;
4625    }
4626
4627    private UserManagerInternal getUserManagerInternal() {
4628        if (mUserManagerInternal == null) {
4629            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4630        }
4631        return mUserManagerInternal;
4632    }
4633
4634    private ActivityManagerInternal getActivityManagerInternal() {
4635        if (mActivityManagerInternal == null) {
4636            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4637        }
4638        return mActivityManagerInternal;
4639    }
4640
4641
4642    private DeviceIdleController.LocalService getDeviceIdleController() {
4643        if (mDeviceIdleController == null) {
4644            mDeviceIdleController =
4645                    LocalServices.getService(DeviceIdleController.LocalService.class);
4646        }
4647        return mDeviceIdleController;
4648    }
4649
4650    /**
4651     * Update given flags when being used to request {@link PackageInfo}.
4652     */
4653    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4654        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4655        boolean triaged = true;
4656        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4657                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4658            // Caller is asking for component details, so they'd better be
4659            // asking for specific encryption matching behavior, or be triaged
4660            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4661                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4662                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4663                triaged = false;
4664            }
4665        }
4666        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4667                | PackageManager.MATCH_SYSTEM_ONLY
4668                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4669            triaged = false;
4670        }
4671        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4672            mPermissionManager.enforceCrossUserPermission(
4673                    Binder.getCallingUid(), userId, false, false,
4674                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4675                    + Debug.getCallers(5));
4676        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4677                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4678            // If the caller wants all packages and has a restricted profile associated with it,
4679            // then match all users. This is to make sure that launchers that need to access work
4680            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4681            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4682            flags |= PackageManager.MATCH_ANY_USER;
4683        }
4684        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4685            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4686                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4687        }
4688        return updateFlags(flags, userId);
4689    }
4690
4691    /**
4692     * Update given flags when being used to request {@link ApplicationInfo}.
4693     */
4694    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4695        return updateFlagsForPackage(flags, userId, cookie);
4696    }
4697
4698    /**
4699     * Update given flags when being used to request {@link ComponentInfo}.
4700     */
4701    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4702        if (cookie instanceof Intent) {
4703            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4704                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4705            }
4706        }
4707
4708        boolean triaged = true;
4709        // Caller is asking for component details, so they'd better be
4710        // asking for specific encryption matching behavior, or be triaged
4711        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4712                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4713                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4714            triaged = false;
4715        }
4716        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4717            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4718                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4719        }
4720
4721        return updateFlags(flags, userId);
4722    }
4723
4724    /**
4725     * Update given intent when being used to request {@link ResolveInfo}.
4726     */
4727    private Intent updateIntentForResolve(Intent intent) {
4728        if (intent.getSelector() != null) {
4729            intent = intent.getSelector();
4730        }
4731        if (DEBUG_PREFERRED) {
4732            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4733        }
4734        return intent;
4735    }
4736
4737    /**
4738     * Update given flags when being used to request {@link ResolveInfo}.
4739     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4740     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4741     * flag set. However, this flag is only honoured in three circumstances:
4742     * <ul>
4743     * <li>when called from a system process</li>
4744     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4745     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4746     * action and a {@code android.intent.category.BROWSABLE} category</li>
4747     * </ul>
4748     */
4749    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4750        return updateFlagsForResolve(flags, userId, intent, callingUid,
4751                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4752    }
4753    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4754            boolean wantInstantApps) {
4755        return updateFlagsForResolve(flags, userId, intent, callingUid,
4756                wantInstantApps, false /*onlyExposedExplicitly*/);
4757    }
4758    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4759            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4760        // Safe mode means we shouldn't match any third-party components
4761        if (mSafeMode) {
4762            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4763        }
4764        if (getInstantAppPackageName(callingUid) != null) {
4765            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4766            if (onlyExposedExplicitly) {
4767                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4768            }
4769            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4770            flags |= PackageManager.MATCH_INSTANT;
4771        } else {
4772            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4773            final boolean allowMatchInstant = wantInstantApps
4774                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4775            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4776                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4777            if (!allowMatchInstant) {
4778                flags &= ~PackageManager.MATCH_INSTANT;
4779            }
4780        }
4781        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4782    }
4783
4784    @Override
4785    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4786        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4787    }
4788
4789    /**
4790     * Important: The provided filterCallingUid is used exclusively to filter out activities
4791     * that can be seen based on user state. It's typically the original caller uid prior
4792     * to clearing. Because it can only be provided by trusted code, it's value can be
4793     * trusted and will be used as-is; unlike userId which will be validated by this method.
4794     */
4795    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4796            int filterCallingUid, int userId) {
4797        if (!sUserManager.exists(userId)) return null;
4798        flags = updateFlagsForComponent(flags, userId, component);
4799
4800        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4801            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4802                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4803        }
4804
4805        synchronized (mPackages) {
4806            PackageParser.Activity a = mActivities.mActivities.get(component);
4807
4808            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4809            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4810                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4811                if (ps == null) return null;
4812                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4813                    return null;
4814                }
4815                return PackageParser.generateActivityInfo(
4816                        a, flags, ps.readUserState(userId), userId);
4817            }
4818            if (mResolveComponentName.equals(component)) {
4819                return PackageParser.generateActivityInfo(
4820                        mResolveActivity, flags, new PackageUserState(), userId);
4821            }
4822        }
4823        return null;
4824    }
4825
4826    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4827        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4828            return false;
4829        }
4830        final long token = Binder.clearCallingIdentity();
4831        try {
4832            final int callingUserId = UserHandle.getUserId(callingUid);
4833            if (ActivityManager.getCurrentUser() != callingUserId) {
4834                return false;
4835            }
4836            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4837        } finally {
4838            Binder.restoreCallingIdentity(token);
4839        }
4840    }
4841
4842    @Override
4843    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4844            String resolvedType) {
4845        synchronized (mPackages) {
4846            if (component.equals(mResolveComponentName)) {
4847                // The resolver supports EVERYTHING!
4848                return true;
4849            }
4850            final int callingUid = Binder.getCallingUid();
4851            final int callingUserId = UserHandle.getUserId(callingUid);
4852            PackageParser.Activity a = mActivities.mActivities.get(component);
4853            if (a == null) {
4854                return false;
4855            }
4856            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4857            if (ps == null) {
4858                return false;
4859            }
4860            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4861                return false;
4862            }
4863            for (int i=0; i<a.intents.size(); i++) {
4864                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4865                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4866                    return true;
4867                }
4868            }
4869            return false;
4870        }
4871    }
4872
4873    @Override
4874    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4875        if (!sUserManager.exists(userId)) return null;
4876        final int callingUid = Binder.getCallingUid();
4877        flags = updateFlagsForComponent(flags, userId, component);
4878        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4879                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4880        synchronized (mPackages) {
4881            PackageParser.Activity a = mReceivers.mActivities.get(component);
4882            if (DEBUG_PACKAGE_INFO) Log.v(
4883                TAG, "getReceiverInfo " + component + ": " + a);
4884            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4885                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4886                if (ps == null) return null;
4887                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4888                    return null;
4889                }
4890                return PackageParser.generateActivityInfo(
4891                        a, flags, ps.readUserState(userId), userId);
4892            }
4893        }
4894        return null;
4895    }
4896
4897    @Override
4898    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4899            int flags, int userId) {
4900        if (!sUserManager.exists(userId)) return null;
4901        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4902        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4903            return null;
4904        }
4905
4906        flags = updateFlagsForPackage(flags, userId, null);
4907
4908        final boolean canSeeStaticLibraries =
4909                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4910                        == PERMISSION_GRANTED
4911                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4912                        == PERMISSION_GRANTED
4913                || canRequestPackageInstallsInternal(packageName,
4914                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4915                        false  /* throwIfPermNotDeclared*/)
4916                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4917                        == PERMISSION_GRANTED;
4918
4919        synchronized (mPackages) {
4920            List<SharedLibraryInfo> result = null;
4921
4922            final int libCount = mSharedLibraries.size();
4923            for (int i = 0; i < libCount; i++) {
4924                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4925                if (versionedLib == null) {
4926                    continue;
4927                }
4928
4929                final int versionCount = versionedLib.size();
4930                for (int j = 0; j < versionCount; j++) {
4931                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4932                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4933                        break;
4934                    }
4935                    final long identity = Binder.clearCallingIdentity();
4936                    try {
4937                        PackageInfo packageInfo = getPackageInfoVersioned(
4938                                libInfo.getDeclaringPackage(), flags
4939                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4940                        if (packageInfo == null) {
4941                            continue;
4942                        }
4943                    } finally {
4944                        Binder.restoreCallingIdentity(identity);
4945                    }
4946
4947                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4948                            libInfo.getLongVersion(), libInfo.getType(),
4949                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4950                            flags, userId));
4951
4952                    if (result == null) {
4953                        result = new ArrayList<>();
4954                    }
4955                    result.add(resLibInfo);
4956                }
4957            }
4958
4959            return result != null ? new ParceledListSlice<>(result) : null;
4960        }
4961    }
4962
4963    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4964            SharedLibraryInfo libInfo, int flags, int userId) {
4965        List<VersionedPackage> versionedPackages = null;
4966        final int packageCount = mSettings.mPackages.size();
4967        for (int i = 0; i < packageCount; i++) {
4968            PackageSetting ps = mSettings.mPackages.valueAt(i);
4969
4970            if (ps == null) {
4971                continue;
4972            }
4973
4974            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4975                continue;
4976            }
4977
4978            final String libName = libInfo.getName();
4979            if (libInfo.isStatic()) {
4980                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4981                if (libIdx < 0) {
4982                    continue;
4983                }
4984                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
4985                    continue;
4986                }
4987                if (versionedPackages == null) {
4988                    versionedPackages = new ArrayList<>();
4989                }
4990                // If the dependent is a static shared lib, use the public package name
4991                String dependentPackageName = ps.name;
4992                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4993                    dependentPackageName = ps.pkg.manifestPackageName;
4994                }
4995                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4996            } else if (ps.pkg != null) {
4997                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4998                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4999                    if (versionedPackages == null) {
5000                        versionedPackages = new ArrayList<>();
5001                    }
5002                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5003                }
5004            }
5005        }
5006
5007        return versionedPackages;
5008    }
5009
5010    @Override
5011    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5012        if (!sUserManager.exists(userId)) return null;
5013        final int callingUid = Binder.getCallingUid();
5014        flags = updateFlagsForComponent(flags, userId, component);
5015        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5016                false /* requireFullPermission */, false /* checkShell */, "get service info");
5017        synchronized (mPackages) {
5018            PackageParser.Service s = mServices.mServices.get(component);
5019            if (DEBUG_PACKAGE_INFO) Log.v(
5020                TAG, "getServiceInfo " + component + ": " + s);
5021            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5022                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5023                if (ps == null) return null;
5024                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5025                    return null;
5026                }
5027                return PackageParser.generateServiceInfo(
5028                        s, flags, ps.readUserState(userId), userId);
5029            }
5030        }
5031        return null;
5032    }
5033
5034    @Override
5035    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5036        if (!sUserManager.exists(userId)) return null;
5037        final int callingUid = Binder.getCallingUid();
5038        flags = updateFlagsForComponent(flags, userId, component);
5039        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5040                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5041        synchronized (mPackages) {
5042            PackageParser.Provider p = mProviders.mProviders.get(component);
5043            if (DEBUG_PACKAGE_INFO) Log.v(
5044                TAG, "getProviderInfo " + component + ": " + p);
5045            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5046                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5047                if (ps == null) return null;
5048                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5049                    return null;
5050                }
5051                return PackageParser.generateProviderInfo(
5052                        p, flags, ps.readUserState(userId), userId);
5053            }
5054        }
5055        return null;
5056    }
5057
5058    @Override
5059    public String[] getSystemSharedLibraryNames() {
5060        // allow instant applications
5061        synchronized (mPackages) {
5062            Set<String> libs = null;
5063            final int libCount = mSharedLibraries.size();
5064            for (int i = 0; i < libCount; i++) {
5065                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5066                if (versionedLib == null) {
5067                    continue;
5068                }
5069                final int versionCount = versionedLib.size();
5070                for (int j = 0; j < versionCount; j++) {
5071                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5072                    if (!libEntry.info.isStatic()) {
5073                        if (libs == null) {
5074                            libs = new ArraySet<>();
5075                        }
5076                        libs.add(libEntry.info.getName());
5077                        break;
5078                    }
5079                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5080                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5081                            UserHandle.getUserId(Binder.getCallingUid()),
5082                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5083                        if (libs == null) {
5084                            libs = new ArraySet<>();
5085                        }
5086                        libs.add(libEntry.info.getName());
5087                        break;
5088                    }
5089                }
5090            }
5091
5092            if (libs != null) {
5093                String[] libsArray = new String[libs.size()];
5094                libs.toArray(libsArray);
5095                return libsArray;
5096            }
5097
5098            return null;
5099        }
5100    }
5101
5102    @Override
5103    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5104        // allow instant applications
5105        synchronized (mPackages) {
5106            return mServicesSystemSharedLibraryPackageName;
5107        }
5108    }
5109
5110    @Override
5111    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5112        // allow instant applications
5113        synchronized (mPackages) {
5114            return mSharedSystemSharedLibraryPackageName;
5115        }
5116    }
5117
5118    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5119        for (int i = userList.length - 1; i >= 0; --i) {
5120            final int userId = userList[i];
5121            // don't add instant app to the list of updates
5122            if (pkgSetting.getInstantApp(userId)) {
5123                continue;
5124            }
5125            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5126            if (changedPackages == null) {
5127                changedPackages = new SparseArray<>();
5128                mChangedPackages.put(userId, changedPackages);
5129            }
5130            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5131            if (sequenceNumbers == null) {
5132                sequenceNumbers = new HashMap<>();
5133                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5134            }
5135            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5136            if (sequenceNumber != null) {
5137                changedPackages.remove(sequenceNumber);
5138            }
5139            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5140            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5141        }
5142        mChangedPackagesSequenceNumber++;
5143    }
5144
5145    @Override
5146    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5147        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5148            return null;
5149        }
5150        synchronized (mPackages) {
5151            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5152                return null;
5153            }
5154            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5155            if (changedPackages == null) {
5156                return null;
5157            }
5158            final List<String> packageNames =
5159                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5160            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5161                final String packageName = changedPackages.get(i);
5162                if (packageName != null) {
5163                    packageNames.add(packageName);
5164                }
5165            }
5166            return packageNames.isEmpty()
5167                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5168        }
5169    }
5170
5171    @Override
5172    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5173        // allow instant applications
5174        ArrayList<FeatureInfo> res;
5175        synchronized (mAvailableFeatures) {
5176            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5177            res.addAll(mAvailableFeatures.values());
5178        }
5179        final FeatureInfo fi = new FeatureInfo();
5180        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5181                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5182        res.add(fi);
5183
5184        return new ParceledListSlice<>(res);
5185    }
5186
5187    @Override
5188    public boolean hasSystemFeature(String name, int version) {
5189        // allow instant applications
5190        synchronized (mAvailableFeatures) {
5191            final FeatureInfo feat = mAvailableFeatures.get(name);
5192            if (feat == null) {
5193                return false;
5194            } else {
5195                return feat.version >= version;
5196            }
5197        }
5198    }
5199
5200    @Override
5201    public int checkPermission(String permName, String pkgName, int userId) {
5202        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5203    }
5204
5205    @Override
5206    public int checkUidPermission(String permName, int uid) {
5207        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5208    }
5209
5210    @Override
5211    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5212        if (UserHandle.getCallingUserId() != userId) {
5213            mContext.enforceCallingPermission(
5214                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5215                    "isPermissionRevokedByPolicy for user " + userId);
5216        }
5217
5218        if (checkPermission(permission, packageName, userId)
5219                == PackageManager.PERMISSION_GRANTED) {
5220            return false;
5221        }
5222
5223        final int callingUid = Binder.getCallingUid();
5224        if (getInstantAppPackageName(callingUid) != null) {
5225            if (!isCallerSameApp(packageName, callingUid)) {
5226                return false;
5227            }
5228        } else {
5229            if (isInstantApp(packageName, userId)) {
5230                return false;
5231            }
5232        }
5233
5234        final long identity = Binder.clearCallingIdentity();
5235        try {
5236            final int flags = getPermissionFlags(permission, packageName, userId);
5237            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5238        } finally {
5239            Binder.restoreCallingIdentity(identity);
5240        }
5241    }
5242
5243    @Override
5244    public String getPermissionControllerPackageName() {
5245        synchronized (mPackages) {
5246            return mRequiredInstallerPackage;
5247        }
5248    }
5249
5250    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5251        return mPermissionManager.addDynamicPermission(
5252                info, async, getCallingUid(), new PermissionCallback() {
5253                    @Override
5254                    public void onPermissionChanged() {
5255                        if (!async) {
5256                            mSettings.writeLPr();
5257                        } else {
5258                            scheduleWriteSettingsLocked();
5259                        }
5260                    }
5261                });
5262    }
5263
5264    @Override
5265    public boolean addPermission(PermissionInfo info) {
5266        synchronized (mPackages) {
5267            return addDynamicPermission(info, false);
5268        }
5269    }
5270
5271    @Override
5272    public boolean addPermissionAsync(PermissionInfo info) {
5273        synchronized (mPackages) {
5274            return addDynamicPermission(info, true);
5275        }
5276    }
5277
5278    @Override
5279    public void removePermission(String permName) {
5280        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5281    }
5282
5283    @Override
5284    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5285        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5286                getCallingUid(), userId, mPermissionCallback);
5287    }
5288
5289    @Override
5290    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5291        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5292                getCallingUid(), userId, mPermissionCallback);
5293    }
5294
5295    @Override
5296    public void resetRuntimePermissions() {
5297        mContext.enforceCallingOrSelfPermission(
5298                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5299                "revokeRuntimePermission");
5300
5301        int callingUid = Binder.getCallingUid();
5302        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5303            mContext.enforceCallingOrSelfPermission(
5304                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5305                    "resetRuntimePermissions");
5306        }
5307
5308        synchronized (mPackages) {
5309            mPermissionManager.updateAllPermissions(
5310                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5311                    mPermissionCallback);
5312            for (int userId : UserManagerService.getInstance().getUserIds()) {
5313                final int packageCount = mPackages.size();
5314                for (int i = 0; i < packageCount; i++) {
5315                    PackageParser.Package pkg = mPackages.valueAt(i);
5316                    if (!(pkg.mExtras instanceof PackageSetting)) {
5317                        continue;
5318                    }
5319                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5320                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5321                }
5322            }
5323        }
5324    }
5325
5326    @Override
5327    public int getPermissionFlags(String permName, String packageName, int userId) {
5328        return mPermissionManager.getPermissionFlags(
5329                permName, packageName, getCallingUid(), userId);
5330    }
5331
5332    @Override
5333    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5334            int flagValues, int userId) {
5335        mPermissionManager.updatePermissionFlags(
5336                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5337                mPermissionCallback);
5338    }
5339
5340    /**
5341     * Update the permission flags for all packages and runtime permissions of a user in order
5342     * to allow device or profile owner to remove POLICY_FIXED.
5343     */
5344    @Override
5345    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5346        synchronized (mPackages) {
5347            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5348                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5349                    mPermissionCallback);
5350            if (changed) {
5351                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5352            }
5353        }
5354    }
5355
5356    @Override
5357    public boolean shouldShowRequestPermissionRationale(String permissionName,
5358            String packageName, int userId) {
5359        if (UserHandle.getCallingUserId() != userId) {
5360            mContext.enforceCallingPermission(
5361                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5362                    "canShowRequestPermissionRationale for user " + userId);
5363        }
5364
5365        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5366        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5367            return false;
5368        }
5369
5370        if (checkPermission(permissionName, packageName, userId)
5371                == PackageManager.PERMISSION_GRANTED) {
5372            return false;
5373        }
5374
5375        final int flags;
5376
5377        final long identity = Binder.clearCallingIdentity();
5378        try {
5379            flags = getPermissionFlags(permissionName,
5380                    packageName, userId);
5381        } finally {
5382            Binder.restoreCallingIdentity(identity);
5383        }
5384
5385        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5386                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5387                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5388
5389        if ((flags & fixedFlags) != 0) {
5390            return false;
5391        }
5392
5393        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5394    }
5395
5396    @Override
5397    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5398        mContext.enforceCallingOrSelfPermission(
5399                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5400                "addOnPermissionsChangeListener");
5401
5402        synchronized (mPackages) {
5403            mOnPermissionChangeListeners.addListenerLocked(listener);
5404        }
5405    }
5406
5407    @Override
5408    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5409        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5410            throw new SecurityException("Instant applications don't have access to this method");
5411        }
5412        synchronized (mPackages) {
5413            mOnPermissionChangeListeners.removeListenerLocked(listener);
5414        }
5415    }
5416
5417    @Override
5418    public boolean isProtectedBroadcast(String actionName) {
5419        // allow instant applications
5420        synchronized (mProtectedBroadcasts) {
5421            if (mProtectedBroadcasts.contains(actionName)) {
5422                return true;
5423            } else if (actionName != null) {
5424                // TODO: remove these terrible hacks
5425                if (actionName.startsWith("android.net.netmon.lingerExpired")
5426                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5427                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5428                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5429                    return true;
5430                }
5431            }
5432        }
5433        return false;
5434    }
5435
5436    @Override
5437    public int checkSignatures(String pkg1, String pkg2) {
5438        synchronized (mPackages) {
5439            final PackageParser.Package p1 = mPackages.get(pkg1);
5440            final PackageParser.Package p2 = mPackages.get(pkg2);
5441            if (p1 == null || p1.mExtras == null
5442                    || p2 == null || p2.mExtras == null) {
5443                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5444            }
5445            final int callingUid = Binder.getCallingUid();
5446            final int callingUserId = UserHandle.getUserId(callingUid);
5447            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5448            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5449            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5450                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5451                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5452            }
5453            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5454        }
5455    }
5456
5457    @Override
5458    public int checkUidSignatures(int uid1, int uid2) {
5459        final int callingUid = Binder.getCallingUid();
5460        final int callingUserId = UserHandle.getUserId(callingUid);
5461        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5462        // Map to base uids.
5463        uid1 = UserHandle.getAppId(uid1);
5464        uid2 = UserHandle.getAppId(uid2);
5465        // reader
5466        synchronized (mPackages) {
5467            Signature[] s1;
5468            Signature[] s2;
5469            Object obj = mSettings.getUserIdLPr(uid1);
5470            if (obj != null) {
5471                if (obj instanceof SharedUserSetting) {
5472                    if (isCallerInstantApp) {
5473                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5474                    }
5475                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5476                } else if (obj instanceof PackageSetting) {
5477                    final PackageSetting ps = (PackageSetting) obj;
5478                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5479                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5480                    }
5481                    s1 = ps.signatures.mSigningDetails.signatures;
5482                } else {
5483                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5484                }
5485            } else {
5486                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5487            }
5488            obj = mSettings.getUserIdLPr(uid2);
5489            if (obj != null) {
5490                if (obj instanceof SharedUserSetting) {
5491                    if (isCallerInstantApp) {
5492                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5493                    }
5494                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5495                } else if (obj instanceof PackageSetting) {
5496                    final PackageSetting ps = (PackageSetting) obj;
5497                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5498                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5499                    }
5500                    s2 = ps.signatures.mSigningDetails.signatures;
5501                } else {
5502                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5503                }
5504            } else {
5505                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5506            }
5507            return compareSignatures(s1, s2);
5508        }
5509    }
5510
5511    @Override
5512    public boolean hasSigningCertificate(
5513            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5514
5515        synchronized (mPackages) {
5516            final PackageParser.Package p = mPackages.get(packageName);
5517            if (p == null || p.mExtras == null) {
5518                return false;
5519            }
5520            final int callingUid = Binder.getCallingUid();
5521            final int callingUserId = UserHandle.getUserId(callingUid);
5522            final PackageSetting ps = (PackageSetting) p.mExtras;
5523            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5524                return false;
5525            }
5526            switch (type) {
5527                case CERT_INPUT_RAW_X509:
5528                    return p.mSigningDetails.hasCertificate(certificate);
5529                case CERT_INPUT_SHA256:
5530                    return p.mSigningDetails.hasSha256Certificate(certificate);
5531                default:
5532                    return false;
5533            }
5534        }
5535    }
5536
5537    @Override
5538    public boolean hasUidSigningCertificate(
5539            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5540        final int callingUid = Binder.getCallingUid();
5541        final int callingUserId = UserHandle.getUserId(callingUid);
5542        // Map to base uids.
5543        uid = UserHandle.getAppId(uid);
5544        // reader
5545        synchronized (mPackages) {
5546            final PackageParser.SigningDetails signingDetails;
5547            final Object obj = mSettings.getUserIdLPr(uid);
5548            if (obj != null) {
5549                if (obj instanceof SharedUserSetting) {
5550                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5551                    if (isCallerInstantApp) {
5552                        return false;
5553                    }
5554                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5555                } else if (obj instanceof PackageSetting) {
5556                    final PackageSetting ps = (PackageSetting) obj;
5557                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5558                        return false;
5559                    }
5560                    signingDetails = ps.signatures.mSigningDetails;
5561                } else {
5562                    return false;
5563                }
5564            } else {
5565                return false;
5566            }
5567            switch (type) {
5568                case CERT_INPUT_RAW_X509:
5569                    return signingDetails.hasCertificate(certificate);
5570                case CERT_INPUT_SHA256:
5571                    return signingDetails.hasSha256Certificate(certificate);
5572                default:
5573                    return false;
5574            }
5575        }
5576    }
5577
5578    /**
5579     * This method should typically only be used when granting or revoking
5580     * permissions, since the app may immediately restart after this call.
5581     * <p>
5582     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5583     * guard your work against the app being relaunched.
5584     */
5585    private void killUid(int appId, int userId, String reason) {
5586        final long identity = Binder.clearCallingIdentity();
5587        try {
5588            IActivityManager am = ActivityManager.getService();
5589            if (am != null) {
5590                try {
5591                    am.killUid(appId, userId, reason);
5592                } catch (RemoteException e) {
5593                    /* ignore - same process */
5594                }
5595            }
5596        } finally {
5597            Binder.restoreCallingIdentity(identity);
5598        }
5599    }
5600
5601    /**
5602     * If the database version for this type of package (internal storage or
5603     * external storage) is less than the version where package signatures
5604     * were updated, return true.
5605     */
5606    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5607        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5608        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5609    }
5610
5611    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5612        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5613        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5614    }
5615
5616    @Override
5617    public List<String> getAllPackages() {
5618        final int callingUid = Binder.getCallingUid();
5619        final int callingUserId = UserHandle.getUserId(callingUid);
5620        synchronized (mPackages) {
5621            if (canViewInstantApps(callingUid, callingUserId)) {
5622                return new ArrayList<String>(mPackages.keySet());
5623            }
5624            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5625            final List<String> result = new ArrayList<>();
5626            if (instantAppPkgName != null) {
5627                // caller is an instant application; filter unexposed applications
5628                for (PackageParser.Package pkg : mPackages.values()) {
5629                    if (!pkg.visibleToInstantApps) {
5630                        continue;
5631                    }
5632                    result.add(pkg.packageName);
5633                }
5634            } else {
5635                // caller is a normal application; filter instant applications
5636                for (PackageParser.Package pkg : mPackages.values()) {
5637                    final PackageSetting ps =
5638                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5639                    if (ps != null
5640                            && ps.getInstantApp(callingUserId)
5641                            && !mInstantAppRegistry.isInstantAccessGranted(
5642                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5643                        continue;
5644                    }
5645                    result.add(pkg.packageName);
5646                }
5647            }
5648            return result;
5649        }
5650    }
5651
5652    @Override
5653    public String[] getPackagesForUid(int uid) {
5654        final int callingUid = Binder.getCallingUid();
5655        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5656        final int userId = UserHandle.getUserId(uid);
5657        uid = UserHandle.getAppId(uid);
5658        // reader
5659        synchronized (mPackages) {
5660            Object obj = mSettings.getUserIdLPr(uid);
5661            if (obj instanceof SharedUserSetting) {
5662                if (isCallerInstantApp) {
5663                    return null;
5664                }
5665                final SharedUserSetting sus = (SharedUserSetting) obj;
5666                final int N = sus.packages.size();
5667                String[] res = new String[N];
5668                final Iterator<PackageSetting> it = sus.packages.iterator();
5669                int i = 0;
5670                while (it.hasNext()) {
5671                    PackageSetting ps = it.next();
5672                    if (ps.getInstalled(userId)) {
5673                        res[i++] = ps.name;
5674                    } else {
5675                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5676                    }
5677                }
5678                return res;
5679            } else if (obj instanceof PackageSetting) {
5680                final PackageSetting ps = (PackageSetting) obj;
5681                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5682                    return new String[]{ps.name};
5683                }
5684            }
5685        }
5686        return null;
5687    }
5688
5689    @Override
5690    public String getNameForUid(int uid) {
5691        final int callingUid = Binder.getCallingUid();
5692        if (getInstantAppPackageName(callingUid) != null) {
5693            return null;
5694        }
5695        synchronized (mPackages) {
5696            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5697            if (obj instanceof SharedUserSetting) {
5698                final SharedUserSetting sus = (SharedUserSetting) obj;
5699                return sus.name + ":" + sus.userId;
5700            } else if (obj instanceof PackageSetting) {
5701                final PackageSetting ps = (PackageSetting) obj;
5702                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5703                    return null;
5704                }
5705                return ps.name;
5706            }
5707            return null;
5708        }
5709    }
5710
5711    @Override
5712    public String[] getNamesForUids(int[] uids) {
5713        if (uids == null || uids.length == 0) {
5714            return null;
5715        }
5716        final int callingUid = Binder.getCallingUid();
5717        if (getInstantAppPackageName(callingUid) != null) {
5718            return null;
5719        }
5720        final String[] names = new String[uids.length];
5721        synchronized (mPackages) {
5722            for (int i = uids.length - 1; i >= 0; i--) {
5723                final int uid = uids[i];
5724                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5725                if (obj instanceof SharedUserSetting) {
5726                    final SharedUserSetting sus = (SharedUserSetting) obj;
5727                    names[i] = "shared:" + sus.name;
5728                } else if (obj instanceof PackageSetting) {
5729                    final PackageSetting ps = (PackageSetting) obj;
5730                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5731                        names[i] = null;
5732                    } else {
5733                        names[i] = ps.name;
5734                    }
5735                } else {
5736                    names[i] = null;
5737                }
5738            }
5739        }
5740        return names;
5741    }
5742
5743    @Override
5744    public int getUidForSharedUser(String sharedUserName) {
5745        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5746            return -1;
5747        }
5748        if (sharedUserName == null) {
5749            return -1;
5750        }
5751        // reader
5752        synchronized (mPackages) {
5753            SharedUserSetting suid;
5754            try {
5755                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5756                if (suid != null) {
5757                    return suid.userId;
5758                }
5759            } catch (PackageManagerException ignore) {
5760                // can't happen, but, still need to catch it
5761            }
5762            return -1;
5763        }
5764    }
5765
5766    @Override
5767    public int getFlagsForUid(int uid) {
5768        final int callingUid = Binder.getCallingUid();
5769        if (getInstantAppPackageName(callingUid) != null) {
5770            return 0;
5771        }
5772        synchronized (mPackages) {
5773            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5774            if (obj instanceof SharedUserSetting) {
5775                final SharedUserSetting sus = (SharedUserSetting) obj;
5776                return sus.pkgFlags;
5777            } else if (obj instanceof PackageSetting) {
5778                final PackageSetting ps = (PackageSetting) obj;
5779                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5780                    return 0;
5781                }
5782                return ps.pkgFlags;
5783            }
5784        }
5785        return 0;
5786    }
5787
5788    @Override
5789    public int getPrivateFlagsForUid(int uid) {
5790        final int callingUid = Binder.getCallingUid();
5791        if (getInstantAppPackageName(callingUid) != null) {
5792            return 0;
5793        }
5794        synchronized (mPackages) {
5795            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5796            if (obj instanceof SharedUserSetting) {
5797                final SharedUserSetting sus = (SharedUserSetting) obj;
5798                return sus.pkgPrivateFlags;
5799            } else if (obj instanceof PackageSetting) {
5800                final PackageSetting ps = (PackageSetting) obj;
5801                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5802                    return 0;
5803                }
5804                return ps.pkgPrivateFlags;
5805            }
5806        }
5807        return 0;
5808    }
5809
5810    @Override
5811    public boolean isUidPrivileged(int uid) {
5812        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5813            return false;
5814        }
5815        uid = UserHandle.getAppId(uid);
5816        // reader
5817        synchronized (mPackages) {
5818            Object obj = mSettings.getUserIdLPr(uid);
5819            if (obj instanceof SharedUserSetting) {
5820                final SharedUserSetting sus = (SharedUserSetting) obj;
5821                final Iterator<PackageSetting> it = sus.packages.iterator();
5822                while (it.hasNext()) {
5823                    if (it.next().isPrivileged()) {
5824                        return true;
5825                    }
5826                }
5827            } else if (obj instanceof PackageSetting) {
5828                final PackageSetting ps = (PackageSetting) obj;
5829                return ps.isPrivileged();
5830            }
5831        }
5832        return false;
5833    }
5834
5835    @Override
5836    public String[] getAppOpPermissionPackages(String permName) {
5837        return mPermissionManager.getAppOpPermissionPackages(permName);
5838    }
5839
5840    @Override
5841    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5842            int flags, int userId) {
5843        return resolveIntentInternal(
5844                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5845    }
5846
5847    /**
5848     * Normally instant apps can only be resolved when they're visible to the caller.
5849     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5850     * since we need to allow the system to start any installed application.
5851     */
5852    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5853            int flags, int userId, boolean resolveForStart) {
5854        try {
5855            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5856
5857            if (!sUserManager.exists(userId)) return null;
5858            final int callingUid = Binder.getCallingUid();
5859            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5860            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5861                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5862
5863            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5864            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5865                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5866            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5867
5868            final ResolveInfo bestChoice =
5869                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5870            return bestChoice;
5871        } finally {
5872            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5873        }
5874    }
5875
5876    @Override
5877    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5878        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5879            throw new SecurityException(
5880                    "findPersistentPreferredActivity can only be run by the system");
5881        }
5882        if (!sUserManager.exists(userId)) {
5883            return null;
5884        }
5885        final int callingUid = Binder.getCallingUid();
5886        intent = updateIntentForResolve(intent);
5887        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5888        final int flags = updateFlagsForResolve(
5889                0, userId, intent, callingUid, false /*includeInstantApps*/);
5890        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5891                userId);
5892        synchronized (mPackages) {
5893            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5894                    userId);
5895        }
5896    }
5897
5898    @Override
5899    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5900            IntentFilter filter, int match, ComponentName activity) {
5901        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5902            return;
5903        }
5904        final int userId = UserHandle.getCallingUserId();
5905        if (DEBUG_PREFERRED) {
5906            Log.v(TAG, "setLastChosenActivity intent=" + intent
5907                + " resolvedType=" + resolvedType
5908                + " flags=" + flags
5909                + " filter=" + filter
5910                + " match=" + match
5911                + " activity=" + activity);
5912            filter.dump(new PrintStreamPrinter(System.out), "    ");
5913        }
5914        intent.setComponent(null);
5915        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5916                userId);
5917        // Find any earlier preferred or last chosen entries and nuke them
5918        findPreferredActivity(intent, resolvedType,
5919                flags, query, 0, false, true, false, userId);
5920        // Add the new activity as the last chosen for this filter
5921        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5922                "Setting last chosen");
5923    }
5924
5925    @Override
5926    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5927        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5928            return null;
5929        }
5930        final int userId = UserHandle.getCallingUserId();
5931        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5932        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5933                userId);
5934        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5935                false, false, false, userId);
5936    }
5937
5938    /**
5939     * Returns whether or not instant apps have been disabled remotely.
5940     */
5941    private boolean isEphemeralDisabled() {
5942        return mEphemeralAppsDisabled;
5943    }
5944
5945    private boolean isInstantAppAllowed(
5946            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5947            boolean skipPackageCheck) {
5948        if (mInstantAppResolverConnection == null) {
5949            return false;
5950        }
5951        if (mInstantAppInstallerActivity == null) {
5952            return false;
5953        }
5954        if (intent.getComponent() != null) {
5955            return false;
5956        }
5957        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5958            return false;
5959        }
5960        if (!skipPackageCheck && intent.getPackage() != null) {
5961            return false;
5962        }
5963        if (!intent.isBrowsableWebIntent()) {
5964            // for non web intents, we should not resolve externally if an app already exists to
5965            // handle it or if the caller didn't explicitly request it.
5966            if ((resolvedActivities != null && resolvedActivities.size() != 0)
5967                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
5968                return false;
5969            }
5970        } else if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
5971            return false;
5972        }
5973        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5974        // Or if there's already an ephemeral app installed that handles the action
5975        synchronized (mPackages) {
5976            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5977            for (int n = 0; n < count; n++) {
5978                final ResolveInfo info = resolvedActivities.get(n);
5979                final String packageName = info.activityInfo.packageName;
5980                final PackageSetting ps = mSettings.mPackages.get(packageName);
5981                if (ps != null) {
5982                    // only check domain verification status if the app is not a browser
5983                    if (!info.handleAllWebDataURI) {
5984                        // Try to get the status from User settings first
5985                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5986                        final int status = (int) (packedStatus >> 32);
5987                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5988                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5989                            if (DEBUG_INSTANT) {
5990                                Slog.v(TAG, "DENY instant app;"
5991                                    + " pkg: " + packageName + ", status: " + status);
5992                            }
5993                            return false;
5994                        }
5995                    }
5996                    if (ps.getInstantApp(userId)) {
5997                        if (DEBUG_INSTANT) {
5998                            Slog.v(TAG, "DENY instant app installed;"
5999                                    + " pkg: " + packageName);
6000                        }
6001                        return false;
6002                    }
6003                }
6004            }
6005        }
6006        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6007        return true;
6008    }
6009
6010    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6011            Intent origIntent, String resolvedType, String callingPackage,
6012            Bundle verificationBundle, int userId) {
6013        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6014                new InstantAppRequest(responseObj, origIntent, resolvedType,
6015                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6016        mHandler.sendMessage(msg);
6017    }
6018
6019    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6020            int flags, List<ResolveInfo> query, int userId) {
6021        if (query != null) {
6022            final int N = query.size();
6023            if (N == 1) {
6024                return query.get(0);
6025            } else if (N > 1) {
6026                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6027                // If there is more than one activity with the same priority,
6028                // then let the user decide between them.
6029                ResolveInfo r0 = query.get(0);
6030                ResolveInfo r1 = query.get(1);
6031                if (DEBUG_INTENT_MATCHING || debug) {
6032                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6033                            + r1.activityInfo.name + "=" + r1.priority);
6034                }
6035                // If the first activity has a higher priority, or a different
6036                // default, then it is always desirable to pick it.
6037                if (r0.priority != r1.priority
6038                        || r0.preferredOrder != r1.preferredOrder
6039                        || r0.isDefault != r1.isDefault) {
6040                    return query.get(0);
6041                }
6042                // If we have saved a preference for a preferred activity for
6043                // this Intent, use that.
6044                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6045                        flags, query, r0.priority, true, false, debug, userId);
6046                if (ri != null) {
6047                    return ri;
6048                }
6049                // If we have an ephemeral app, use it
6050                for (int i = 0; i < N; i++) {
6051                    ri = query.get(i);
6052                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6053                        final String packageName = ri.activityInfo.packageName;
6054                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6055                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6056                        final int status = (int)(packedStatus >> 32);
6057                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6058                            return ri;
6059                        }
6060                    }
6061                }
6062                ri = new ResolveInfo(mResolveInfo);
6063                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6064                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6065                // If all of the options come from the same package, show the application's
6066                // label and icon instead of the generic resolver's.
6067                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6068                // and then throw away the ResolveInfo itself, meaning that the caller loses
6069                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6070                // a fallback for this case; we only set the target package's resources on
6071                // the ResolveInfo, not the ActivityInfo.
6072                final String intentPackage = intent.getPackage();
6073                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6074                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6075                    ri.resolvePackageName = intentPackage;
6076                    if (userNeedsBadging(userId)) {
6077                        ri.noResourceId = true;
6078                    } else {
6079                        ri.icon = appi.icon;
6080                    }
6081                    ri.iconResourceId = appi.icon;
6082                    ri.labelRes = appi.labelRes;
6083                }
6084                ri.activityInfo.applicationInfo = new ApplicationInfo(
6085                        ri.activityInfo.applicationInfo);
6086                if (userId != 0) {
6087                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6088                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6089                }
6090                // Make sure that the resolver is displayable in car mode
6091                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6092                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6093                return ri;
6094            }
6095        }
6096        return null;
6097    }
6098
6099    /**
6100     * Return true if the given list is not empty and all of its contents have
6101     * an activityInfo with the given package name.
6102     */
6103    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6104        if (ArrayUtils.isEmpty(list)) {
6105            return false;
6106        }
6107        for (int i = 0, N = list.size(); i < N; i++) {
6108            final ResolveInfo ri = list.get(i);
6109            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6110            if (ai == null || !packageName.equals(ai.packageName)) {
6111                return false;
6112            }
6113        }
6114        return true;
6115    }
6116
6117    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6118            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6119        final int N = query.size();
6120        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6121                .get(userId);
6122        // Get the list of persistent preferred activities that handle the intent
6123        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6124        List<PersistentPreferredActivity> pprefs = ppir != null
6125                ? ppir.queryIntent(intent, resolvedType,
6126                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6127                        userId)
6128                : null;
6129        if (pprefs != null && pprefs.size() > 0) {
6130            final int M = pprefs.size();
6131            for (int i=0; i<M; i++) {
6132                final PersistentPreferredActivity ppa = pprefs.get(i);
6133                if (DEBUG_PREFERRED || debug) {
6134                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6135                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6136                            + "\n  component=" + ppa.mComponent);
6137                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6138                }
6139                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6140                        flags | MATCH_DISABLED_COMPONENTS, userId);
6141                if (DEBUG_PREFERRED || debug) {
6142                    Slog.v(TAG, "Found persistent preferred activity:");
6143                    if (ai != null) {
6144                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6145                    } else {
6146                        Slog.v(TAG, "  null");
6147                    }
6148                }
6149                if (ai == null) {
6150                    // This previously registered persistent preferred activity
6151                    // component is no longer known. Ignore it and do NOT remove it.
6152                    continue;
6153                }
6154                for (int j=0; j<N; j++) {
6155                    final ResolveInfo ri = query.get(j);
6156                    if (!ri.activityInfo.applicationInfo.packageName
6157                            .equals(ai.applicationInfo.packageName)) {
6158                        continue;
6159                    }
6160                    if (!ri.activityInfo.name.equals(ai.name)) {
6161                        continue;
6162                    }
6163                    //  Found a persistent preference that can handle the intent.
6164                    if (DEBUG_PREFERRED || debug) {
6165                        Slog.v(TAG, "Returning persistent preferred activity: " +
6166                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6167                    }
6168                    return ri;
6169                }
6170            }
6171        }
6172        return null;
6173    }
6174
6175    // TODO: handle preferred activities missing while user has amnesia
6176    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6177            List<ResolveInfo> query, int priority, boolean always,
6178            boolean removeMatches, boolean debug, int userId) {
6179        if (!sUserManager.exists(userId)) return null;
6180        final int callingUid = Binder.getCallingUid();
6181        flags = updateFlagsForResolve(
6182                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6183        intent = updateIntentForResolve(intent);
6184        // writer
6185        synchronized (mPackages) {
6186            // Try to find a matching persistent preferred activity.
6187            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6188                    debug, userId);
6189
6190            // If a persistent preferred activity matched, use it.
6191            if (pri != null) {
6192                return pri;
6193            }
6194
6195            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6196            // Get the list of preferred activities that handle the intent
6197            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6198            List<PreferredActivity> prefs = pir != null
6199                    ? pir.queryIntent(intent, resolvedType,
6200                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6201                            userId)
6202                    : null;
6203            if (prefs != null && prefs.size() > 0) {
6204                boolean changed = false;
6205                try {
6206                    // First figure out how good the original match set is.
6207                    // We will only allow preferred activities that came
6208                    // from the same match quality.
6209                    int match = 0;
6210
6211                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6212
6213                    final int N = query.size();
6214                    for (int j=0; j<N; j++) {
6215                        final ResolveInfo ri = query.get(j);
6216                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6217                                + ": 0x" + Integer.toHexString(match));
6218                        if (ri.match > match) {
6219                            match = ri.match;
6220                        }
6221                    }
6222
6223                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6224                            + Integer.toHexString(match));
6225
6226                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6227                    final int M = prefs.size();
6228                    for (int i=0; i<M; i++) {
6229                        final PreferredActivity pa = prefs.get(i);
6230                        if (DEBUG_PREFERRED || debug) {
6231                            Slog.v(TAG, "Checking PreferredActivity ds="
6232                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6233                                    + "\n  component=" + pa.mPref.mComponent);
6234                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6235                        }
6236                        if (pa.mPref.mMatch != match) {
6237                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6238                                    + Integer.toHexString(pa.mPref.mMatch));
6239                            continue;
6240                        }
6241                        // If it's not an "always" type preferred activity and that's what we're
6242                        // looking for, skip it.
6243                        if (always && !pa.mPref.mAlways) {
6244                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6245                            continue;
6246                        }
6247                        final ActivityInfo ai = getActivityInfo(
6248                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6249                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6250                                userId);
6251                        if (DEBUG_PREFERRED || debug) {
6252                            Slog.v(TAG, "Found preferred activity:");
6253                            if (ai != null) {
6254                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6255                            } else {
6256                                Slog.v(TAG, "  null");
6257                            }
6258                        }
6259                        if (ai == null) {
6260                            // This previously registered preferred activity
6261                            // component is no longer known.  Most likely an update
6262                            // to the app was installed and in the new version this
6263                            // component no longer exists.  Clean it up by removing
6264                            // it from the preferred activities list, and skip it.
6265                            Slog.w(TAG, "Removing dangling preferred activity: "
6266                                    + pa.mPref.mComponent);
6267                            pir.removeFilter(pa);
6268                            changed = true;
6269                            continue;
6270                        }
6271                        for (int j=0; j<N; j++) {
6272                            final ResolveInfo ri = query.get(j);
6273                            if (!ri.activityInfo.applicationInfo.packageName
6274                                    .equals(ai.applicationInfo.packageName)) {
6275                                continue;
6276                            }
6277                            if (!ri.activityInfo.name.equals(ai.name)) {
6278                                continue;
6279                            }
6280
6281                            if (removeMatches) {
6282                                pir.removeFilter(pa);
6283                                changed = true;
6284                                if (DEBUG_PREFERRED) {
6285                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6286                                }
6287                                break;
6288                            }
6289
6290                            // Okay we found a previously set preferred or last chosen app.
6291                            // If the result set is different from when this
6292                            // was created, and is not a subset of the preferred set, we need to
6293                            // clear it and re-ask the user their preference, if we're looking for
6294                            // an "always" type entry.
6295                            if (always && !pa.mPref.sameSet(query)) {
6296                                if (pa.mPref.isSuperset(query)) {
6297                                    // some components of the set are no longer present in
6298                                    // the query, but the preferred activity can still be reused
6299                                    if (DEBUG_PREFERRED) {
6300                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6301                                                + " still valid as only non-preferred components"
6302                                                + " were removed for " + intent + " type "
6303                                                + resolvedType);
6304                                    }
6305                                    // remove obsolete components and re-add the up-to-date filter
6306                                    PreferredActivity freshPa = new PreferredActivity(pa,
6307                                            pa.mPref.mMatch,
6308                                            pa.mPref.discardObsoleteComponents(query),
6309                                            pa.mPref.mComponent,
6310                                            pa.mPref.mAlways);
6311                                    pir.removeFilter(pa);
6312                                    pir.addFilter(freshPa);
6313                                    changed = true;
6314                                } else {
6315                                    Slog.i(TAG,
6316                                            "Result set changed, dropping preferred activity for "
6317                                                    + intent + " type " + resolvedType);
6318                                    if (DEBUG_PREFERRED) {
6319                                        Slog.v(TAG, "Removing preferred activity since set changed "
6320                                                + pa.mPref.mComponent);
6321                                    }
6322                                    pir.removeFilter(pa);
6323                                    // Re-add the filter as a "last chosen" entry (!always)
6324                                    PreferredActivity lastChosen = new PreferredActivity(
6325                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6326                                    pir.addFilter(lastChosen);
6327                                    changed = true;
6328                                    return null;
6329                                }
6330                            }
6331
6332                            // Yay! Either the set matched or we're looking for the last chosen
6333                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6334                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6335                            return ri;
6336                        }
6337                    }
6338                } finally {
6339                    if (changed) {
6340                        if (DEBUG_PREFERRED) {
6341                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6342                        }
6343                        scheduleWritePackageRestrictionsLocked(userId);
6344                    }
6345                }
6346            }
6347        }
6348        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6349        return null;
6350    }
6351
6352    /*
6353     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6354     */
6355    @Override
6356    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6357            int targetUserId) {
6358        mContext.enforceCallingOrSelfPermission(
6359                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6360        List<CrossProfileIntentFilter> matches =
6361                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6362        if (matches != null) {
6363            int size = matches.size();
6364            for (int i = 0; i < size; i++) {
6365                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6366            }
6367        }
6368        if (intent.hasWebURI()) {
6369            // cross-profile app linking works only towards the parent.
6370            final int callingUid = Binder.getCallingUid();
6371            final UserInfo parent = getProfileParent(sourceUserId);
6372            synchronized(mPackages) {
6373                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6374                        false /*includeInstantApps*/);
6375                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6376                        intent, resolvedType, flags, sourceUserId, parent.id);
6377                return xpDomainInfo != null;
6378            }
6379        }
6380        return false;
6381    }
6382
6383    private UserInfo getProfileParent(int userId) {
6384        final long identity = Binder.clearCallingIdentity();
6385        try {
6386            return sUserManager.getProfileParent(userId);
6387        } finally {
6388            Binder.restoreCallingIdentity(identity);
6389        }
6390    }
6391
6392    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6393            String resolvedType, int userId) {
6394        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6395        if (resolver != null) {
6396            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6397        }
6398        return null;
6399    }
6400
6401    @Override
6402    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6403            String resolvedType, int flags, int userId) {
6404        try {
6405            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6406
6407            return new ParceledListSlice<>(
6408                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6409        } finally {
6410            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6411        }
6412    }
6413
6414    /**
6415     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6416     * instant, returns {@code null}.
6417     */
6418    private String getInstantAppPackageName(int callingUid) {
6419        synchronized (mPackages) {
6420            // If the caller is an isolated app use the owner's uid for the lookup.
6421            if (Process.isIsolated(callingUid)) {
6422                callingUid = mIsolatedOwners.get(callingUid);
6423            }
6424            final int appId = UserHandle.getAppId(callingUid);
6425            final Object obj = mSettings.getUserIdLPr(appId);
6426            if (obj instanceof PackageSetting) {
6427                final PackageSetting ps = (PackageSetting) obj;
6428                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6429                return isInstantApp ? ps.pkg.packageName : null;
6430            }
6431        }
6432        return null;
6433    }
6434
6435    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6436            String resolvedType, int flags, int userId) {
6437        return queryIntentActivitiesInternal(
6438                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6439                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6440    }
6441
6442    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6443            String resolvedType, int flags, int filterCallingUid, int userId,
6444            boolean resolveForStart, boolean allowDynamicSplits) {
6445        if (!sUserManager.exists(userId)) return Collections.emptyList();
6446        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6447        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6448                false /* requireFullPermission */, false /* checkShell */,
6449                "query intent activities");
6450        final String pkgName = intent.getPackage();
6451        ComponentName comp = intent.getComponent();
6452        if (comp == null) {
6453            if (intent.getSelector() != null) {
6454                intent = intent.getSelector();
6455                comp = intent.getComponent();
6456            }
6457        }
6458
6459        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6460                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6461        if (comp != null) {
6462            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6463            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6464            if (ai != null) {
6465                // When specifying an explicit component, we prevent the activity from being
6466                // used when either 1) the calling package is normal and the activity is within
6467                // an ephemeral application or 2) the calling package is ephemeral and the
6468                // activity is not visible to ephemeral applications.
6469                final boolean matchInstantApp =
6470                        (flags & PackageManager.MATCH_INSTANT) != 0;
6471                final boolean matchVisibleToInstantAppOnly =
6472                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6473                final boolean matchExplicitlyVisibleOnly =
6474                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6475                final boolean isCallerInstantApp =
6476                        instantAppPkgName != null;
6477                final boolean isTargetSameInstantApp =
6478                        comp.getPackageName().equals(instantAppPkgName);
6479                final boolean isTargetInstantApp =
6480                        (ai.applicationInfo.privateFlags
6481                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6482                final boolean isTargetVisibleToInstantApp =
6483                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6484                final boolean isTargetExplicitlyVisibleToInstantApp =
6485                        isTargetVisibleToInstantApp
6486                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6487                final boolean isTargetHiddenFromInstantApp =
6488                        !isTargetVisibleToInstantApp
6489                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6490                final boolean blockResolution =
6491                        !isTargetSameInstantApp
6492                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6493                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6494                                        && isTargetHiddenFromInstantApp));
6495                if (!blockResolution) {
6496                    final ResolveInfo ri = new ResolveInfo();
6497                    ri.activityInfo = ai;
6498                    list.add(ri);
6499                }
6500            }
6501            return applyPostResolutionFilter(
6502                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6503        }
6504
6505        // reader
6506        boolean sortResult = false;
6507        boolean addEphemeral = false;
6508        List<ResolveInfo> result;
6509        final boolean ephemeralDisabled = isEphemeralDisabled();
6510        synchronized (mPackages) {
6511            if (pkgName == null) {
6512                List<CrossProfileIntentFilter> matchingFilters =
6513                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6514                // Check for results that need to skip the current profile.
6515                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6516                        resolvedType, flags, userId);
6517                if (xpResolveInfo != null) {
6518                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6519                    xpResult.add(xpResolveInfo);
6520                    return applyPostResolutionFilter(
6521                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6522                            allowDynamicSplits, filterCallingUid, userId);
6523                }
6524
6525                // Check for results in the current profile.
6526                result = filterIfNotSystemUser(mActivities.queryIntent(
6527                        intent, resolvedType, flags, userId), userId);
6528                addEphemeral = !ephemeralDisabled
6529                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6530                // Check for cross profile results.
6531                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6532                xpResolveInfo = queryCrossProfileIntents(
6533                        matchingFilters, intent, resolvedType, flags, userId,
6534                        hasNonNegativePriorityResult);
6535                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6536                    boolean isVisibleToUser = filterIfNotSystemUser(
6537                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6538                    if (isVisibleToUser) {
6539                        result.add(xpResolveInfo);
6540                        sortResult = true;
6541                    }
6542                }
6543                if (intent.hasWebURI()) {
6544                    CrossProfileDomainInfo xpDomainInfo = null;
6545                    final UserInfo parent = getProfileParent(userId);
6546                    if (parent != null) {
6547                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6548                                flags, userId, parent.id);
6549                    }
6550                    if (xpDomainInfo != null) {
6551                        if (xpResolveInfo != null) {
6552                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6553                            // in the result.
6554                            result.remove(xpResolveInfo);
6555                        }
6556                        if (result.size() == 0 && !addEphemeral) {
6557                            // No result in current profile, but found candidate in parent user.
6558                            // And we are not going to add emphemeral app, so we can return the
6559                            // result straight away.
6560                            result.add(xpDomainInfo.resolveInfo);
6561                            return applyPostResolutionFilter(result, instantAppPkgName,
6562                                    allowDynamicSplits, filterCallingUid, userId);
6563                        }
6564                    } else if (result.size() <= 1 && !addEphemeral) {
6565                        // No result in parent user and <= 1 result in current profile, and we
6566                        // are not going to add emphemeral app, so we can return the result without
6567                        // further processing.
6568                        return applyPostResolutionFilter(result, instantAppPkgName,
6569                                allowDynamicSplits, filterCallingUid, userId);
6570                    }
6571                    // We have more than one candidate (combining results from current and parent
6572                    // profile), so we need filtering and sorting.
6573                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6574                            intent, flags, result, xpDomainInfo, userId);
6575                    sortResult = true;
6576                }
6577            } else {
6578                final PackageParser.Package pkg = mPackages.get(pkgName);
6579                result = null;
6580                if (pkg != null) {
6581                    result = filterIfNotSystemUser(
6582                            mActivities.queryIntentForPackage(
6583                                    intent, resolvedType, flags, pkg.activities, userId),
6584                            userId);
6585                }
6586                if (result == null || result.size() == 0) {
6587                    // the caller wants to resolve for a particular package; however, there
6588                    // were no installed results, so, try to find an ephemeral result
6589                    addEphemeral = !ephemeralDisabled
6590                            && isInstantAppAllowed(
6591                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6592                    if (result == null) {
6593                        result = new ArrayList<>();
6594                    }
6595                }
6596            }
6597        }
6598        if (addEphemeral) {
6599            result = maybeAddInstantAppInstaller(
6600                    result, intent, resolvedType, flags, userId, resolveForStart);
6601        }
6602        if (sortResult) {
6603            Collections.sort(result, mResolvePrioritySorter);
6604        }
6605        return applyPostResolutionFilter(
6606                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6607    }
6608
6609    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6610            String resolvedType, int flags, int userId, boolean resolveForStart) {
6611        // first, check to see if we've got an instant app already installed
6612        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6613        ResolveInfo localInstantApp = null;
6614        boolean blockResolution = false;
6615        if (!alreadyResolvedLocally) {
6616            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6617                    flags
6618                        | PackageManager.GET_RESOLVED_FILTER
6619                        | PackageManager.MATCH_INSTANT
6620                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6621                    userId);
6622            for (int i = instantApps.size() - 1; i >= 0; --i) {
6623                final ResolveInfo info = instantApps.get(i);
6624                final String packageName = info.activityInfo.packageName;
6625                final PackageSetting ps = mSettings.mPackages.get(packageName);
6626                if (ps.getInstantApp(userId)) {
6627                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6628                    final int status = (int)(packedStatus >> 32);
6629                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6630                        // there's a local instant application installed, but, the user has
6631                        // chosen to never use it; skip resolution and don't acknowledge
6632                        // an instant application is even available
6633                        if (DEBUG_INSTANT) {
6634                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6635                        }
6636                        blockResolution = true;
6637                        break;
6638                    } else {
6639                        // we have a locally installed instant application; skip resolution
6640                        // but acknowledge there's an instant application available
6641                        if (DEBUG_INSTANT) {
6642                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6643                        }
6644                        localInstantApp = info;
6645                        break;
6646                    }
6647                }
6648            }
6649        }
6650        // no app installed, let's see if one's available
6651        AuxiliaryResolveInfo auxiliaryResponse = null;
6652        if (!blockResolution) {
6653            if (localInstantApp == null) {
6654                // we don't have an instant app locally, resolve externally
6655                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6656                final InstantAppRequest requestObject = new InstantAppRequest(
6657                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6658                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6659                        resolveForStart);
6660                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6661                        mInstantAppResolverConnection, requestObject);
6662                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6663            } else {
6664                // we have an instant application locally, but, we can't admit that since
6665                // callers shouldn't be able to determine prior browsing. create a dummy
6666                // auxiliary response so the downstream code behaves as if there's an
6667                // instant application available externally. when it comes time to start
6668                // the instant application, we'll do the right thing.
6669                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6670                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6671                                        ai.packageName, ai.versionCode, null /* splitName */);
6672            }
6673        }
6674        if (intent.isBrowsableWebIntent() && auxiliaryResponse == null) {
6675            return result;
6676        }
6677        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6678        if (ps == null) {
6679            return result;
6680        }
6681        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6682        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6683                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6684        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6685                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6686        // add a non-generic filter
6687        ephemeralInstaller.filter = new IntentFilter();
6688        if (intent.getAction() != null) {
6689            ephemeralInstaller.filter.addAction(intent.getAction());
6690        }
6691        if (intent.getData() != null && intent.getData().getPath() != null) {
6692            ephemeralInstaller.filter.addDataPath(
6693                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6694        }
6695        ephemeralInstaller.isInstantAppAvailable = true;
6696        // make sure this resolver is the default
6697        ephemeralInstaller.isDefault = true;
6698        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6699        if (DEBUG_INSTANT) {
6700            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6701        }
6702
6703        result.add(ephemeralInstaller);
6704        return result;
6705    }
6706
6707    private static class CrossProfileDomainInfo {
6708        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6709        ResolveInfo resolveInfo;
6710        /* Best domain verification status of the activities found in the other profile */
6711        int bestDomainVerificationStatus;
6712    }
6713
6714    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6715            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6716        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6717                sourceUserId)) {
6718            return null;
6719        }
6720        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6721                resolvedType, flags, parentUserId);
6722
6723        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6724            return null;
6725        }
6726        CrossProfileDomainInfo result = null;
6727        int size = resultTargetUser.size();
6728        for (int i = 0; i < size; i++) {
6729            ResolveInfo riTargetUser = resultTargetUser.get(i);
6730            // Intent filter verification is only for filters that specify a host. So don't return
6731            // those that handle all web uris.
6732            if (riTargetUser.handleAllWebDataURI) {
6733                continue;
6734            }
6735            String packageName = riTargetUser.activityInfo.packageName;
6736            PackageSetting ps = mSettings.mPackages.get(packageName);
6737            if (ps == null) {
6738                continue;
6739            }
6740            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6741            int status = (int)(verificationState >> 32);
6742            if (result == null) {
6743                result = new CrossProfileDomainInfo();
6744                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6745                        sourceUserId, parentUserId);
6746                result.bestDomainVerificationStatus = status;
6747            } else {
6748                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6749                        result.bestDomainVerificationStatus);
6750            }
6751        }
6752        // Don't consider matches with status NEVER across profiles.
6753        if (result != null && result.bestDomainVerificationStatus
6754                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6755            return null;
6756        }
6757        return result;
6758    }
6759
6760    /**
6761     * Verification statuses are ordered from the worse to the best, except for
6762     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6763     */
6764    private int bestDomainVerificationStatus(int status1, int status2) {
6765        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6766            return status2;
6767        }
6768        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6769            return status1;
6770        }
6771        return (int) MathUtils.max(status1, status2);
6772    }
6773
6774    private boolean isUserEnabled(int userId) {
6775        long callingId = Binder.clearCallingIdentity();
6776        try {
6777            UserInfo userInfo = sUserManager.getUserInfo(userId);
6778            return userInfo != null && userInfo.isEnabled();
6779        } finally {
6780            Binder.restoreCallingIdentity(callingId);
6781        }
6782    }
6783
6784    /**
6785     * Filter out activities with systemUserOnly flag set, when current user is not System.
6786     *
6787     * @return filtered list
6788     */
6789    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6790        if (userId == UserHandle.USER_SYSTEM) {
6791            return resolveInfos;
6792        }
6793        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6794            ResolveInfo info = resolveInfos.get(i);
6795            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6796                resolveInfos.remove(i);
6797            }
6798        }
6799        return resolveInfos;
6800    }
6801
6802    /**
6803     * Filters out ephemeral activities.
6804     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6805     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6806     *
6807     * @param resolveInfos The pre-filtered list of resolved activities
6808     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6809     *          is performed.
6810     * @return A filtered list of resolved activities.
6811     */
6812    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6813            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6814        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6815            final ResolveInfo info = resolveInfos.get(i);
6816            // allow activities that are defined in the provided package
6817            if (allowDynamicSplits
6818                    && info.activityInfo != null
6819                    && info.activityInfo.splitName != null
6820                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6821                            info.activityInfo.splitName)) {
6822                if (mInstantAppInstallerActivity == null) {
6823                    if (DEBUG_INSTALL) {
6824                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6825                    }
6826                    resolveInfos.remove(i);
6827                    continue;
6828                }
6829                // requested activity is defined in a split that hasn't been installed yet.
6830                // add the installer to the resolve list
6831                if (DEBUG_INSTALL) {
6832                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6833                }
6834                final ResolveInfo installerInfo = new ResolveInfo(
6835                        mInstantAppInstallerInfo);
6836                final ComponentName installFailureActivity = findInstallFailureActivity(
6837                        info.activityInfo.packageName,  filterCallingUid, userId);
6838                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6839                        installFailureActivity,
6840                        info.activityInfo.packageName,
6841                        info.activityInfo.applicationInfo.versionCode,
6842                        info.activityInfo.splitName);
6843                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6844                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6845                // add a non-generic filter
6846                installerInfo.filter = new IntentFilter();
6847
6848                // This resolve info may appear in the chooser UI, so let us make it
6849                // look as the one it replaces as far as the user is concerned which
6850                // requires loading the correct label and icon for the resolve info.
6851                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6852                installerInfo.labelRes = info.resolveLabelResId();
6853                installerInfo.icon = info.resolveIconResId();
6854
6855                // propagate priority/preferred order/default
6856                installerInfo.priority = info.priority;
6857                installerInfo.preferredOrder = info.preferredOrder;
6858                installerInfo.isDefault = info.isDefault;
6859                installerInfo.isInstantAppAvailable = true;
6860                resolveInfos.set(i, installerInfo);
6861                continue;
6862            }
6863            // caller is a full app, don't need to apply any other filtering
6864            if (ephemeralPkgName == null) {
6865                continue;
6866            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6867                // caller is same app; don't need to apply any other filtering
6868                continue;
6869            }
6870            // allow activities that have been explicitly exposed to ephemeral apps
6871            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6872            if (!isEphemeralApp
6873                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6874                continue;
6875            }
6876            resolveInfos.remove(i);
6877        }
6878        return resolveInfos;
6879    }
6880
6881    /**
6882     * Returns the activity component that can handle install failures.
6883     * <p>By default, the instant application installer handles failures. However, an
6884     * application may want to handle failures on its own. Applications do this by
6885     * creating an activity with an intent filter that handles the action
6886     * {@link Intent#ACTION_INSTALL_FAILURE}.
6887     */
6888    private @Nullable ComponentName findInstallFailureActivity(
6889            String packageName, int filterCallingUid, int userId) {
6890        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6891        failureActivityIntent.setPackage(packageName);
6892        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6893        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6894                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6895                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6896        final int NR = result.size();
6897        if (NR > 0) {
6898            for (int i = 0; i < NR; i++) {
6899                final ResolveInfo info = result.get(i);
6900                if (info.activityInfo.splitName != null) {
6901                    continue;
6902                }
6903                return new ComponentName(packageName, info.activityInfo.name);
6904            }
6905        }
6906        return null;
6907    }
6908
6909    /**
6910     * @param resolveInfos list of resolve infos in descending priority order
6911     * @return if the list contains a resolve info with non-negative priority
6912     */
6913    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6914        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6915    }
6916
6917    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6918            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6919            int userId) {
6920        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6921
6922        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6923            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6924                    candidates.size());
6925        }
6926
6927        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6928        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6929        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6930        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6931        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6932        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6933
6934        synchronized (mPackages) {
6935            final int count = candidates.size();
6936            // First, try to use linked apps. Partition the candidates into four lists:
6937            // one for the final results, one for the "do not use ever", one for "undefined status"
6938            // and finally one for "browser app type".
6939            for (int n=0; n<count; n++) {
6940                ResolveInfo info = candidates.get(n);
6941                String packageName = info.activityInfo.packageName;
6942                PackageSetting ps = mSettings.mPackages.get(packageName);
6943                if (ps != null) {
6944                    // Add to the special match all list (Browser use case)
6945                    if (info.handleAllWebDataURI) {
6946                        matchAllList.add(info);
6947                        continue;
6948                    }
6949                    // Try to get the status from User settings first
6950                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6951                    int status = (int)(packedStatus >> 32);
6952                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6953                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6954                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6955                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6956                                    + " : linkgen=" + linkGeneration);
6957                        }
6958                        // Use link-enabled generation as preferredOrder, i.e.
6959                        // prefer newly-enabled over earlier-enabled.
6960                        info.preferredOrder = linkGeneration;
6961                        alwaysList.add(info);
6962                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6963                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6964                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6965                        }
6966                        neverList.add(info);
6967                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6968                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6969                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6970                        }
6971                        alwaysAskList.add(info);
6972                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6973                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6974                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6975                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6976                        }
6977                        undefinedList.add(info);
6978                    }
6979                }
6980            }
6981
6982            // We'll want to include browser possibilities in a few cases
6983            boolean includeBrowser = false;
6984
6985            // First try to add the "always" resolution(s) for the current user, if any
6986            if (alwaysList.size() > 0) {
6987                result.addAll(alwaysList);
6988            } else {
6989                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6990                result.addAll(undefinedList);
6991                // Maybe add one for the other profile.
6992                if (xpDomainInfo != null && (
6993                        xpDomainInfo.bestDomainVerificationStatus
6994                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6995                    result.add(xpDomainInfo.resolveInfo);
6996                }
6997                includeBrowser = true;
6998            }
6999
7000            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7001            // If there were 'always' entries their preferred order has been set, so we also
7002            // back that off to make the alternatives equivalent
7003            if (alwaysAskList.size() > 0) {
7004                for (ResolveInfo i : result) {
7005                    i.preferredOrder = 0;
7006                }
7007                result.addAll(alwaysAskList);
7008                includeBrowser = true;
7009            }
7010
7011            if (includeBrowser) {
7012                // Also add browsers (all of them or only the default one)
7013                if (DEBUG_DOMAIN_VERIFICATION) {
7014                    Slog.v(TAG, "   ...including browsers in candidate set");
7015                }
7016                if ((matchFlags & MATCH_ALL) != 0) {
7017                    result.addAll(matchAllList);
7018                } else {
7019                    // Browser/generic handling case.  If there's a default browser, go straight
7020                    // to that (but only if there is no other higher-priority match).
7021                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7022                    int maxMatchPrio = 0;
7023                    ResolveInfo defaultBrowserMatch = null;
7024                    final int numCandidates = matchAllList.size();
7025                    for (int n = 0; n < numCandidates; n++) {
7026                        ResolveInfo info = matchAllList.get(n);
7027                        // track the highest overall match priority...
7028                        if (info.priority > maxMatchPrio) {
7029                            maxMatchPrio = info.priority;
7030                        }
7031                        // ...and the highest-priority default browser match
7032                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7033                            if (defaultBrowserMatch == null
7034                                    || (defaultBrowserMatch.priority < info.priority)) {
7035                                if (debug) {
7036                                    Slog.v(TAG, "Considering default browser match " + info);
7037                                }
7038                                defaultBrowserMatch = info;
7039                            }
7040                        }
7041                    }
7042                    if (defaultBrowserMatch != null
7043                            && defaultBrowserMatch.priority >= maxMatchPrio
7044                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7045                    {
7046                        if (debug) {
7047                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7048                        }
7049                        result.add(defaultBrowserMatch);
7050                    } else {
7051                        result.addAll(matchAllList);
7052                    }
7053                }
7054
7055                // If there is nothing selected, add all candidates and remove the ones that the user
7056                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7057                if (result.size() == 0) {
7058                    result.addAll(candidates);
7059                    result.removeAll(neverList);
7060                }
7061            }
7062        }
7063        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7064            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7065                    result.size());
7066            for (ResolveInfo info : result) {
7067                Slog.v(TAG, "  + " + info.activityInfo);
7068            }
7069        }
7070        return result;
7071    }
7072
7073    // Returns a packed value as a long:
7074    //
7075    // high 'int'-sized word: link status: undefined/ask/never/always.
7076    // low 'int'-sized word: relative priority among 'always' results.
7077    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7078        long result = ps.getDomainVerificationStatusForUser(userId);
7079        // if none available, get the master status
7080        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7081            if (ps.getIntentFilterVerificationInfo() != null) {
7082                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7083            }
7084        }
7085        return result;
7086    }
7087
7088    private ResolveInfo querySkipCurrentProfileIntents(
7089            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7090            int flags, int sourceUserId) {
7091        if (matchingFilters != null) {
7092            int size = matchingFilters.size();
7093            for (int i = 0; i < size; i ++) {
7094                CrossProfileIntentFilter filter = matchingFilters.get(i);
7095                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7096                    // Checking if there are activities in the target user that can handle the
7097                    // intent.
7098                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7099                            resolvedType, flags, sourceUserId);
7100                    if (resolveInfo != null) {
7101                        return resolveInfo;
7102                    }
7103                }
7104            }
7105        }
7106        return null;
7107    }
7108
7109    // Return matching ResolveInfo in target user if any.
7110    private ResolveInfo queryCrossProfileIntents(
7111            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7112            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7113        if (matchingFilters != null) {
7114            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7115            // match the same intent. For performance reasons, it is better not to
7116            // run queryIntent twice for the same userId
7117            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7118            int size = matchingFilters.size();
7119            for (int i = 0; i < size; i++) {
7120                CrossProfileIntentFilter filter = matchingFilters.get(i);
7121                int targetUserId = filter.getTargetUserId();
7122                boolean skipCurrentProfile =
7123                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7124                boolean skipCurrentProfileIfNoMatchFound =
7125                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7126                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7127                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7128                    // Checking if there are activities in the target user that can handle the
7129                    // intent.
7130                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7131                            resolvedType, flags, sourceUserId);
7132                    if (resolveInfo != null) return resolveInfo;
7133                    alreadyTriedUserIds.put(targetUserId, true);
7134                }
7135            }
7136        }
7137        return null;
7138    }
7139
7140    /**
7141     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7142     * will forward the intent to the filter's target user.
7143     * Otherwise, returns null.
7144     */
7145    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7146            String resolvedType, int flags, int sourceUserId) {
7147        int targetUserId = filter.getTargetUserId();
7148        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7149                resolvedType, flags, targetUserId);
7150        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7151            // If all the matches in the target profile are suspended, return null.
7152            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7153                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7154                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7155                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7156                            targetUserId);
7157                }
7158            }
7159        }
7160        return null;
7161    }
7162
7163    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7164            int sourceUserId, int targetUserId) {
7165        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7166        long ident = Binder.clearCallingIdentity();
7167        boolean targetIsProfile;
7168        try {
7169            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7170        } finally {
7171            Binder.restoreCallingIdentity(ident);
7172        }
7173        String className;
7174        if (targetIsProfile) {
7175            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7176        } else {
7177            className = FORWARD_INTENT_TO_PARENT;
7178        }
7179        ComponentName forwardingActivityComponentName = new ComponentName(
7180                mAndroidApplication.packageName, className);
7181        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7182                sourceUserId);
7183        if (!targetIsProfile) {
7184            forwardingActivityInfo.showUserIcon = targetUserId;
7185            forwardingResolveInfo.noResourceId = true;
7186        }
7187        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7188        forwardingResolveInfo.priority = 0;
7189        forwardingResolveInfo.preferredOrder = 0;
7190        forwardingResolveInfo.match = 0;
7191        forwardingResolveInfo.isDefault = true;
7192        forwardingResolveInfo.filter = filter;
7193        forwardingResolveInfo.targetUserId = targetUserId;
7194        return forwardingResolveInfo;
7195    }
7196
7197    @Override
7198    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7199            Intent[] specifics, String[] specificTypes, Intent intent,
7200            String resolvedType, int flags, int userId) {
7201        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7202                specificTypes, intent, resolvedType, flags, userId));
7203    }
7204
7205    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7206            Intent[] specifics, String[] specificTypes, Intent intent,
7207            String resolvedType, int flags, int userId) {
7208        if (!sUserManager.exists(userId)) return Collections.emptyList();
7209        final int callingUid = Binder.getCallingUid();
7210        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7211                false /*includeInstantApps*/);
7212        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7213                false /*requireFullPermission*/, false /*checkShell*/,
7214                "query intent activity options");
7215        final String resultsAction = intent.getAction();
7216
7217        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7218                | PackageManager.GET_RESOLVED_FILTER, userId);
7219
7220        if (DEBUG_INTENT_MATCHING) {
7221            Log.v(TAG, "Query " + intent + ": " + results);
7222        }
7223
7224        int specificsPos = 0;
7225        int N;
7226
7227        // todo: note that the algorithm used here is O(N^2).  This
7228        // isn't a problem in our current environment, but if we start running
7229        // into situations where we have more than 5 or 10 matches then this
7230        // should probably be changed to something smarter...
7231
7232        // First we go through and resolve each of the specific items
7233        // that were supplied, taking care of removing any corresponding
7234        // duplicate items in the generic resolve list.
7235        if (specifics != null) {
7236            for (int i=0; i<specifics.length; i++) {
7237                final Intent sintent = specifics[i];
7238                if (sintent == null) {
7239                    continue;
7240                }
7241
7242                if (DEBUG_INTENT_MATCHING) {
7243                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7244                }
7245
7246                String action = sintent.getAction();
7247                if (resultsAction != null && resultsAction.equals(action)) {
7248                    // If this action was explicitly requested, then don't
7249                    // remove things that have it.
7250                    action = null;
7251                }
7252
7253                ResolveInfo ri = null;
7254                ActivityInfo ai = null;
7255
7256                ComponentName comp = sintent.getComponent();
7257                if (comp == null) {
7258                    ri = resolveIntent(
7259                        sintent,
7260                        specificTypes != null ? specificTypes[i] : null,
7261                            flags, userId);
7262                    if (ri == null) {
7263                        continue;
7264                    }
7265                    if (ri == mResolveInfo) {
7266                        // ACK!  Must do something better with this.
7267                    }
7268                    ai = ri.activityInfo;
7269                    comp = new ComponentName(ai.applicationInfo.packageName,
7270                            ai.name);
7271                } else {
7272                    ai = getActivityInfo(comp, flags, userId);
7273                    if (ai == null) {
7274                        continue;
7275                    }
7276                }
7277
7278                // Look for any generic query activities that are duplicates
7279                // of this specific one, and remove them from the results.
7280                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7281                N = results.size();
7282                int j;
7283                for (j=specificsPos; j<N; j++) {
7284                    ResolveInfo sri = results.get(j);
7285                    if ((sri.activityInfo.name.equals(comp.getClassName())
7286                            && sri.activityInfo.applicationInfo.packageName.equals(
7287                                    comp.getPackageName()))
7288                        || (action != null && sri.filter.matchAction(action))) {
7289                        results.remove(j);
7290                        if (DEBUG_INTENT_MATCHING) Log.v(
7291                            TAG, "Removing duplicate item from " + j
7292                            + " due to specific " + specificsPos);
7293                        if (ri == null) {
7294                            ri = sri;
7295                        }
7296                        j--;
7297                        N--;
7298                    }
7299                }
7300
7301                // Add this specific item to its proper place.
7302                if (ri == null) {
7303                    ri = new ResolveInfo();
7304                    ri.activityInfo = ai;
7305                }
7306                results.add(specificsPos, ri);
7307                ri.specificIndex = i;
7308                specificsPos++;
7309            }
7310        }
7311
7312        // Now we go through the remaining generic results and remove any
7313        // duplicate actions that are found here.
7314        N = results.size();
7315        for (int i=specificsPos; i<N-1; i++) {
7316            final ResolveInfo rii = results.get(i);
7317            if (rii.filter == null) {
7318                continue;
7319            }
7320
7321            // Iterate over all of the actions of this result's intent
7322            // filter...  typically this should be just one.
7323            final Iterator<String> it = rii.filter.actionsIterator();
7324            if (it == null) {
7325                continue;
7326            }
7327            while (it.hasNext()) {
7328                final String action = it.next();
7329                if (resultsAction != null && resultsAction.equals(action)) {
7330                    // If this action was explicitly requested, then don't
7331                    // remove things that have it.
7332                    continue;
7333                }
7334                for (int j=i+1; j<N; j++) {
7335                    final ResolveInfo rij = results.get(j);
7336                    if (rij.filter != null && rij.filter.hasAction(action)) {
7337                        results.remove(j);
7338                        if (DEBUG_INTENT_MATCHING) Log.v(
7339                            TAG, "Removing duplicate item from " + j
7340                            + " due to action " + action + " at " + i);
7341                        j--;
7342                        N--;
7343                    }
7344                }
7345            }
7346
7347            // If the caller didn't request filter information, drop it now
7348            // so we don't have to marshall/unmarshall it.
7349            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7350                rii.filter = null;
7351            }
7352        }
7353
7354        // Filter out the caller activity if so requested.
7355        if (caller != null) {
7356            N = results.size();
7357            for (int i=0; i<N; i++) {
7358                ActivityInfo ainfo = results.get(i).activityInfo;
7359                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7360                        && caller.getClassName().equals(ainfo.name)) {
7361                    results.remove(i);
7362                    break;
7363                }
7364            }
7365        }
7366
7367        // If the caller didn't request filter information,
7368        // drop them now so we don't have to
7369        // marshall/unmarshall it.
7370        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7371            N = results.size();
7372            for (int i=0; i<N; i++) {
7373                results.get(i).filter = null;
7374            }
7375        }
7376
7377        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7378        return results;
7379    }
7380
7381    @Override
7382    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7383            String resolvedType, int flags, int userId) {
7384        return new ParceledListSlice<>(
7385                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7386                        false /*allowDynamicSplits*/));
7387    }
7388
7389    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7390            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7391        if (!sUserManager.exists(userId)) return Collections.emptyList();
7392        final int callingUid = Binder.getCallingUid();
7393        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7394                false /*requireFullPermission*/, false /*checkShell*/,
7395                "query intent receivers");
7396        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7397        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7398                false /*includeInstantApps*/);
7399        ComponentName comp = intent.getComponent();
7400        if (comp == null) {
7401            if (intent.getSelector() != null) {
7402                intent = intent.getSelector();
7403                comp = intent.getComponent();
7404            }
7405        }
7406        if (comp != null) {
7407            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7408            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7409            if (ai != null) {
7410                // When specifying an explicit component, we prevent the activity from being
7411                // used when either 1) the calling package is normal and the activity is within
7412                // an instant application or 2) the calling package is ephemeral and the
7413                // activity is not visible to instant applications.
7414                final boolean matchInstantApp =
7415                        (flags & PackageManager.MATCH_INSTANT) != 0;
7416                final boolean matchVisibleToInstantAppOnly =
7417                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7418                final boolean matchExplicitlyVisibleOnly =
7419                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7420                final boolean isCallerInstantApp =
7421                        instantAppPkgName != null;
7422                final boolean isTargetSameInstantApp =
7423                        comp.getPackageName().equals(instantAppPkgName);
7424                final boolean isTargetInstantApp =
7425                        (ai.applicationInfo.privateFlags
7426                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7427                final boolean isTargetVisibleToInstantApp =
7428                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7429                final boolean isTargetExplicitlyVisibleToInstantApp =
7430                        isTargetVisibleToInstantApp
7431                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7432                final boolean isTargetHiddenFromInstantApp =
7433                        !isTargetVisibleToInstantApp
7434                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7435                final boolean blockResolution =
7436                        !isTargetSameInstantApp
7437                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7438                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7439                                        && isTargetHiddenFromInstantApp));
7440                if (!blockResolution) {
7441                    ResolveInfo ri = new ResolveInfo();
7442                    ri.activityInfo = ai;
7443                    list.add(ri);
7444                }
7445            }
7446            return applyPostResolutionFilter(
7447                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7448        }
7449
7450        // reader
7451        synchronized (mPackages) {
7452            String pkgName = intent.getPackage();
7453            if (pkgName == null) {
7454                final List<ResolveInfo> result =
7455                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7456                return applyPostResolutionFilter(
7457                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7458            }
7459            final PackageParser.Package pkg = mPackages.get(pkgName);
7460            if (pkg != null) {
7461                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7462                        intent, resolvedType, flags, pkg.receivers, userId);
7463                return applyPostResolutionFilter(
7464                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7465            }
7466            return Collections.emptyList();
7467        }
7468    }
7469
7470    @Override
7471    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7472        final int callingUid = Binder.getCallingUid();
7473        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7474    }
7475
7476    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7477            int userId, int callingUid) {
7478        if (!sUserManager.exists(userId)) return null;
7479        flags = updateFlagsForResolve(
7480                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7481        List<ResolveInfo> query = queryIntentServicesInternal(
7482                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7483        if (query != null) {
7484            if (query.size() >= 1) {
7485                // If there is more than one service with the same priority,
7486                // just arbitrarily pick the first one.
7487                return query.get(0);
7488            }
7489        }
7490        return null;
7491    }
7492
7493    @Override
7494    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7495            String resolvedType, int flags, int userId) {
7496        final int callingUid = Binder.getCallingUid();
7497        return new ParceledListSlice<>(queryIntentServicesInternal(
7498                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7499    }
7500
7501    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7502            String resolvedType, int flags, int userId, int callingUid,
7503            boolean includeInstantApps) {
7504        if (!sUserManager.exists(userId)) return Collections.emptyList();
7505        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7506                false /*requireFullPermission*/, false /*checkShell*/,
7507                "query intent receivers");
7508        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7509        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7510        ComponentName comp = intent.getComponent();
7511        if (comp == null) {
7512            if (intent.getSelector() != null) {
7513                intent = intent.getSelector();
7514                comp = intent.getComponent();
7515            }
7516        }
7517        if (comp != null) {
7518            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7519            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7520            if (si != null) {
7521                // When specifying an explicit component, we prevent the service from being
7522                // used when either 1) the service is in an instant application and the
7523                // caller is not the same instant application or 2) the calling package is
7524                // ephemeral and the activity is not visible to ephemeral applications.
7525                final boolean matchInstantApp =
7526                        (flags & PackageManager.MATCH_INSTANT) != 0;
7527                final boolean matchVisibleToInstantAppOnly =
7528                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7529                final boolean isCallerInstantApp =
7530                        instantAppPkgName != null;
7531                final boolean isTargetSameInstantApp =
7532                        comp.getPackageName().equals(instantAppPkgName);
7533                final boolean isTargetInstantApp =
7534                        (si.applicationInfo.privateFlags
7535                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7536                final boolean isTargetHiddenFromInstantApp =
7537                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7538                final boolean blockResolution =
7539                        !isTargetSameInstantApp
7540                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7541                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7542                                        && isTargetHiddenFromInstantApp));
7543                if (!blockResolution) {
7544                    final ResolveInfo ri = new ResolveInfo();
7545                    ri.serviceInfo = si;
7546                    list.add(ri);
7547                }
7548            }
7549            return list;
7550        }
7551
7552        // reader
7553        synchronized (mPackages) {
7554            String pkgName = intent.getPackage();
7555            if (pkgName == null) {
7556                return applyPostServiceResolutionFilter(
7557                        mServices.queryIntent(intent, resolvedType, flags, userId),
7558                        instantAppPkgName);
7559            }
7560            final PackageParser.Package pkg = mPackages.get(pkgName);
7561            if (pkg != null) {
7562                return applyPostServiceResolutionFilter(
7563                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7564                                userId),
7565                        instantAppPkgName);
7566            }
7567            return Collections.emptyList();
7568        }
7569    }
7570
7571    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7572            String instantAppPkgName) {
7573        if (instantAppPkgName == null) {
7574            return resolveInfos;
7575        }
7576        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7577            final ResolveInfo info = resolveInfos.get(i);
7578            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7579            // allow services that are defined in the provided package
7580            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7581                if (info.serviceInfo.splitName != null
7582                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7583                                info.serviceInfo.splitName)) {
7584                    // requested service is defined in a split that hasn't been installed yet.
7585                    // add the installer to the resolve list
7586                    if (DEBUG_INSTANT) {
7587                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7588                    }
7589                    final ResolveInfo installerInfo = new ResolveInfo(
7590                            mInstantAppInstallerInfo);
7591                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7592                            null /* installFailureActivity */,
7593                            info.serviceInfo.packageName,
7594                            info.serviceInfo.applicationInfo.versionCode,
7595                            info.serviceInfo.splitName);
7596                    // make sure this resolver is the default
7597                    installerInfo.isDefault = true;
7598                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7599                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7600                    // add a non-generic filter
7601                    installerInfo.filter = new IntentFilter();
7602                    // load resources from the correct package
7603                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7604                    resolveInfos.set(i, installerInfo);
7605                }
7606                continue;
7607            }
7608            // allow services that have been explicitly exposed to ephemeral apps
7609            if (!isEphemeralApp
7610                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7611                continue;
7612            }
7613            resolveInfos.remove(i);
7614        }
7615        return resolveInfos;
7616    }
7617
7618    @Override
7619    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7620            String resolvedType, int flags, int userId) {
7621        return new ParceledListSlice<>(
7622                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7623    }
7624
7625    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7626            Intent intent, String resolvedType, int flags, int userId) {
7627        if (!sUserManager.exists(userId)) return Collections.emptyList();
7628        final int callingUid = Binder.getCallingUid();
7629        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7630        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7631                false /*includeInstantApps*/);
7632        ComponentName comp = intent.getComponent();
7633        if (comp == null) {
7634            if (intent.getSelector() != null) {
7635                intent = intent.getSelector();
7636                comp = intent.getComponent();
7637            }
7638        }
7639        if (comp != null) {
7640            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7641            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7642            if (pi != null) {
7643                // When specifying an explicit component, we prevent the provider from being
7644                // used when either 1) the provider is in an instant application and the
7645                // caller is not the same instant application or 2) the calling package is an
7646                // instant application and the provider is not visible to instant applications.
7647                final boolean matchInstantApp =
7648                        (flags & PackageManager.MATCH_INSTANT) != 0;
7649                final boolean matchVisibleToInstantAppOnly =
7650                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7651                final boolean isCallerInstantApp =
7652                        instantAppPkgName != null;
7653                final boolean isTargetSameInstantApp =
7654                        comp.getPackageName().equals(instantAppPkgName);
7655                final boolean isTargetInstantApp =
7656                        (pi.applicationInfo.privateFlags
7657                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7658                final boolean isTargetHiddenFromInstantApp =
7659                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7660                final boolean blockResolution =
7661                        !isTargetSameInstantApp
7662                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7663                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7664                                        && isTargetHiddenFromInstantApp));
7665                if (!blockResolution) {
7666                    final ResolveInfo ri = new ResolveInfo();
7667                    ri.providerInfo = pi;
7668                    list.add(ri);
7669                }
7670            }
7671            return list;
7672        }
7673
7674        // reader
7675        synchronized (mPackages) {
7676            String pkgName = intent.getPackage();
7677            if (pkgName == null) {
7678                return applyPostContentProviderResolutionFilter(
7679                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7680                        instantAppPkgName);
7681            }
7682            final PackageParser.Package pkg = mPackages.get(pkgName);
7683            if (pkg != null) {
7684                return applyPostContentProviderResolutionFilter(
7685                        mProviders.queryIntentForPackage(
7686                        intent, resolvedType, flags, pkg.providers, userId),
7687                        instantAppPkgName);
7688            }
7689            return Collections.emptyList();
7690        }
7691    }
7692
7693    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7694            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7695        if (instantAppPkgName == null) {
7696            return resolveInfos;
7697        }
7698        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7699            final ResolveInfo info = resolveInfos.get(i);
7700            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7701            // allow providers that are defined in the provided package
7702            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7703                if (info.providerInfo.splitName != null
7704                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7705                                info.providerInfo.splitName)) {
7706                    // requested provider is defined in a split that hasn't been installed yet.
7707                    // add the installer to the resolve list
7708                    if (DEBUG_INSTANT) {
7709                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7710                    }
7711                    final ResolveInfo installerInfo = new ResolveInfo(
7712                            mInstantAppInstallerInfo);
7713                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7714                            null /*failureActivity*/,
7715                            info.providerInfo.packageName,
7716                            info.providerInfo.applicationInfo.versionCode,
7717                            info.providerInfo.splitName);
7718                    // make sure this resolver is the default
7719                    installerInfo.isDefault = true;
7720                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7721                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7722                    // add a non-generic filter
7723                    installerInfo.filter = new IntentFilter();
7724                    // load resources from the correct package
7725                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7726                    resolveInfos.set(i, installerInfo);
7727                }
7728                continue;
7729            }
7730            // allow providers that have been explicitly exposed to instant applications
7731            if (!isEphemeralApp
7732                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7733                continue;
7734            }
7735            resolveInfos.remove(i);
7736        }
7737        return resolveInfos;
7738    }
7739
7740    @Override
7741    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7742        final int callingUid = Binder.getCallingUid();
7743        if (getInstantAppPackageName(callingUid) != null) {
7744            return ParceledListSlice.emptyList();
7745        }
7746        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7747        flags = updateFlagsForPackage(flags, userId, null);
7748        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7749        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7750                true /* requireFullPermission */, false /* checkShell */,
7751                "get installed packages");
7752
7753        // writer
7754        synchronized (mPackages) {
7755            ArrayList<PackageInfo> list;
7756            if (listUninstalled) {
7757                list = new ArrayList<>(mSettings.mPackages.size());
7758                for (PackageSetting ps : mSettings.mPackages.values()) {
7759                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7760                        continue;
7761                    }
7762                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7763                        continue;
7764                    }
7765                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7766                    if (pi != null) {
7767                        list.add(pi);
7768                    }
7769                }
7770            } else {
7771                list = new ArrayList<>(mPackages.size());
7772                for (PackageParser.Package p : mPackages.values()) {
7773                    final PackageSetting ps = (PackageSetting) p.mExtras;
7774                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7775                        continue;
7776                    }
7777                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7778                        continue;
7779                    }
7780                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7781                            p.mExtras, flags, userId);
7782                    if (pi != null) {
7783                        list.add(pi);
7784                    }
7785                }
7786            }
7787
7788            return new ParceledListSlice<>(list);
7789        }
7790    }
7791
7792    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7793            String[] permissions, boolean[] tmp, int flags, int userId) {
7794        int numMatch = 0;
7795        final PermissionsState permissionsState = ps.getPermissionsState();
7796        for (int i=0; i<permissions.length; i++) {
7797            final String permission = permissions[i];
7798            if (permissionsState.hasPermission(permission, userId)) {
7799                tmp[i] = true;
7800                numMatch++;
7801            } else {
7802                tmp[i] = false;
7803            }
7804        }
7805        if (numMatch == 0) {
7806            return;
7807        }
7808        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7809
7810        // The above might return null in cases of uninstalled apps or install-state
7811        // skew across users/profiles.
7812        if (pi != null) {
7813            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7814                if (numMatch == permissions.length) {
7815                    pi.requestedPermissions = permissions;
7816                } else {
7817                    pi.requestedPermissions = new String[numMatch];
7818                    numMatch = 0;
7819                    for (int i=0; i<permissions.length; i++) {
7820                        if (tmp[i]) {
7821                            pi.requestedPermissions[numMatch] = permissions[i];
7822                            numMatch++;
7823                        }
7824                    }
7825                }
7826            }
7827            list.add(pi);
7828        }
7829    }
7830
7831    @Override
7832    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7833            String[] permissions, int flags, int userId) {
7834        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7835        flags = updateFlagsForPackage(flags, userId, permissions);
7836        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7837                true /* requireFullPermission */, false /* checkShell */,
7838                "get packages holding permissions");
7839        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7840
7841        // writer
7842        synchronized (mPackages) {
7843            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7844            boolean[] tmpBools = new boolean[permissions.length];
7845            if (listUninstalled) {
7846                for (PackageSetting ps : mSettings.mPackages.values()) {
7847                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7848                            userId);
7849                }
7850            } else {
7851                for (PackageParser.Package pkg : mPackages.values()) {
7852                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7853                    if (ps != null) {
7854                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7855                                userId);
7856                    }
7857                }
7858            }
7859
7860            return new ParceledListSlice<PackageInfo>(list);
7861        }
7862    }
7863
7864    @Override
7865    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7866        final int callingUid = Binder.getCallingUid();
7867        if (getInstantAppPackageName(callingUid) != null) {
7868            return ParceledListSlice.emptyList();
7869        }
7870        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7871        flags = updateFlagsForApplication(flags, userId, null);
7872        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7873
7874        // writer
7875        synchronized (mPackages) {
7876            ArrayList<ApplicationInfo> list;
7877            if (listUninstalled) {
7878                list = new ArrayList<>(mSettings.mPackages.size());
7879                for (PackageSetting ps : mSettings.mPackages.values()) {
7880                    ApplicationInfo ai;
7881                    int effectiveFlags = flags;
7882                    if (ps.isSystem()) {
7883                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7884                    }
7885                    if (ps.pkg != null) {
7886                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7887                            continue;
7888                        }
7889                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7890                            continue;
7891                        }
7892                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7893                                ps.readUserState(userId), userId);
7894                        if (ai != null) {
7895                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7896                        }
7897                    } else {
7898                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7899                        // and already converts to externally visible package name
7900                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7901                                callingUid, effectiveFlags, userId);
7902                    }
7903                    if (ai != null) {
7904                        list.add(ai);
7905                    }
7906                }
7907            } else {
7908                list = new ArrayList<>(mPackages.size());
7909                for (PackageParser.Package p : mPackages.values()) {
7910                    if (p.mExtras != null) {
7911                        PackageSetting ps = (PackageSetting) p.mExtras;
7912                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7913                            continue;
7914                        }
7915                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7916                            continue;
7917                        }
7918                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7919                                ps.readUserState(userId), userId);
7920                        if (ai != null) {
7921                            ai.packageName = resolveExternalPackageNameLPr(p);
7922                            list.add(ai);
7923                        }
7924                    }
7925                }
7926            }
7927
7928            return new ParceledListSlice<>(list);
7929        }
7930    }
7931
7932    @Override
7933    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7934        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7935            return null;
7936        }
7937        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7938            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7939                    "getEphemeralApplications");
7940        }
7941        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7942                true /* requireFullPermission */, false /* checkShell */,
7943                "getEphemeralApplications");
7944        synchronized (mPackages) {
7945            List<InstantAppInfo> instantApps = mInstantAppRegistry
7946                    .getInstantAppsLPr(userId);
7947            if (instantApps != null) {
7948                return new ParceledListSlice<>(instantApps);
7949            }
7950        }
7951        return null;
7952    }
7953
7954    @Override
7955    public boolean isInstantApp(String packageName, int userId) {
7956        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7957                true /* requireFullPermission */, false /* checkShell */,
7958                "isInstantApp");
7959        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7960            return false;
7961        }
7962
7963        synchronized (mPackages) {
7964            int callingUid = Binder.getCallingUid();
7965            if (Process.isIsolated(callingUid)) {
7966                callingUid = mIsolatedOwners.get(callingUid);
7967            }
7968            final PackageSetting ps = mSettings.mPackages.get(packageName);
7969            PackageParser.Package pkg = mPackages.get(packageName);
7970            final boolean returnAllowed =
7971                    ps != null
7972                    && (isCallerSameApp(packageName, callingUid)
7973                            || canViewInstantApps(callingUid, userId)
7974                            || mInstantAppRegistry.isInstantAccessGranted(
7975                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7976            if (returnAllowed) {
7977                return ps.getInstantApp(userId);
7978            }
7979        }
7980        return false;
7981    }
7982
7983    @Override
7984    public byte[] getInstantAppCookie(String packageName, int userId) {
7985        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7986            return null;
7987        }
7988
7989        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7990                true /* requireFullPermission */, false /* checkShell */,
7991                "getInstantAppCookie");
7992        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7993            return null;
7994        }
7995        synchronized (mPackages) {
7996            return mInstantAppRegistry.getInstantAppCookieLPw(
7997                    packageName, userId);
7998        }
7999    }
8000
8001    @Override
8002    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8003        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8004            return true;
8005        }
8006
8007        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8008                true /* requireFullPermission */, true /* checkShell */,
8009                "setInstantAppCookie");
8010        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8011            return false;
8012        }
8013        synchronized (mPackages) {
8014            return mInstantAppRegistry.setInstantAppCookieLPw(
8015                    packageName, cookie, userId);
8016        }
8017    }
8018
8019    @Override
8020    public Bitmap getInstantAppIcon(String packageName, int userId) {
8021        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8022            return null;
8023        }
8024
8025        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8026            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8027                    "getInstantAppIcon");
8028        }
8029        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8030                true /* requireFullPermission */, false /* checkShell */,
8031                "getInstantAppIcon");
8032
8033        synchronized (mPackages) {
8034            return mInstantAppRegistry.getInstantAppIconLPw(
8035                    packageName, userId);
8036        }
8037    }
8038
8039    private boolean isCallerSameApp(String packageName, int uid) {
8040        PackageParser.Package pkg = mPackages.get(packageName);
8041        return pkg != null
8042                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8043    }
8044
8045    @Override
8046    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8047        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8048            return ParceledListSlice.emptyList();
8049        }
8050        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8051    }
8052
8053    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8054        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8055
8056        // reader
8057        synchronized (mPackages) {
8058            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8059            final int userId = UserHandle.getCallingUserId();
8060            while (i.hasNext()) {
8061                final PackageParser.Package p = i.next();
8062                if (p.applicationInfo == null) continue;
8063
8064                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8065                        && !p.applicationInfo.isDirectBootAware();
8066                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8067                        && p.applicationInfo.isDirectBootAware();
8068
8069                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8070                        && (!mSafeMode || isSystemApp(p))
8071                        && (matchesUnaware || matchesAware)) {
8072                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8073                    if (ps != null) {
8074                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8075                                ps.readUserState(userId), userId);
8076                        if (ai != null) {
8077                            finalList.add(ai);
8078                        }
8079                    }
8080                }
8081            }
8082        }
8083
8084        return finalList;
8085    }
8086
8087    @Override
8088    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8089        return resolveContentProviderInternal(name, flags, userId);
8090    }
8091
8092    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8093        if (!sUserManager.exists(userId)) return null;
8094        flags = updateFlagsForComponent(flags, userId, name);
8095        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8096        // reader
8097        synchronized (mPackages) {
8098            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8099            PackageSetting ps = provider != null
8100                    ? mSettings.mPackages.get(provider.owner.packageName)
8101                    : null;
8102            if (ps != null) {
8103                final boolean isInstantApp = ps.getInstantApp(userId);
8104                // normal application; filter out instant application provider
8105                if (instantAppPkgName == null && isInstantApp) {
8106                    return null;
8107                }
8108                // instant application; filter out other instant applications
8109                if (instantAppPkgName != null
8110                        && isInstantApp
8111                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8112                    return null;
8113                }
8114                // instant application; filter out non-exposed provider
8115                if (instantAppPkgName != null
8116                        && !isInstantApp
8117                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8118                    return null;
8119                }
8120                // provider not enabled
8121                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8122                    return null;
8123                }
8124                return PackageParser.generateProviderInfo(
8125                        provider, flags, ps.readUserState(userId), userId);
8126            }
8127            return null;
8128        }
8129    }
8130
8131    /**
8132     * @deprecated
8133     */
8134    @Deprecated
8135    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8136        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8137            return;
8138        }
8139        // reader
8140        synchronized (mPackages) {
8141            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8142                    .entrySet().iterator();
8143            final int userId = UserHandle.getCallingUserId();
8144            while (i.hasNext()) {
8145                Map.Entry<String, PackageParser.Provider> entry = i.next();
8146                PackageParser.Provider p = entry.getValue();
8147                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8148
8149                if (ps != null && p.syncable
8150                        && (!mSafeMode || (p.info.applicationInfo.flags
8151                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8152                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8153                            ps.readUserState(userId), userId);
8154                    if (info != null) {
8155                        outNames.add(entry.getKey());
8156                        outInfo.add(info);
8157                    }
8158                }
8159            }
8160        }
8161    }
8162
8163    @Override
8164    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8165            int uid, int flags, String metaDataKey) {
8166        final int callingUid = Binder.getCallingUid();
8167        final int userId = processName != null ? UserHandle.getUserId(uid)
8168                : UserHandle.getCallingUserId();
8169        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8170        flags = updateFlagsForComponent(flags, userId, processName);
8171        ArrayList<ProviderInfo> finalList = null;
8172        // reader
8173        synchronized (mPackages) {
8174            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8175            while (i.hasNext()) {
8176                final PackageParser.Provider p = i.next();
8177                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8178                if (ps != null && p.info.authority != null
8179                        && (processName == null
8180                                || (p.info.processName.equals(processName)
8181                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8182                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8183
8184                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8185                    // parameter.
8186                    if (metaDataKey != null
8187                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8188                        continue;
8189                    }
8190                    final ComponentName component =
8191                            new ComponentName(p.info.packageName, p.info.name);
8192                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8193                        continue;
8194                    }
8195                    if (finalList == null) {
8196                        finalList = new ArrayList<ProviderInfo>(3);
8197                    }
8198                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8199                            ps.readUserState(userId), userId);
8200                    if (info != null) {
8201                        finalList.add(info);
8202                    }
8203                }
8204            }
8205        }
8206
8207        if (finalList != null) {
8208            Collections.sort(finalList, mProviderInitOrderSorter);
8209            return new ParceledListSlice<ProviderInfo>(finalList);
8210        }
8211
8212        return ParceledListSlice.emptyList();
8213    }
8214
8215    @Override
8216    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8217        // reader
8218        synchronized (mPackages) {
8219            final int callingUid = Binder.getCallingUid();
8220            final int callingUserId = UserHandle.getUserId(callingUid);
8221            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8222            if (ps == null) return null;
8223            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8224                return null;
8225            }
8226            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8227            return PackageParser.generateInstrumentationInfo(i, flags);
8228        }
8229    }
8230
8231    @Override
8232    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8233            String targetPackage, int flags) {
8234        final int callingUid = Binder.getCallingUid();
8235        final int callingUserId = UserHandle.getUserId(callingUid);
8236        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8237        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8238            return ParceledListSlice.emptyList();
8239        }
8240        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8241    }
8242
8243    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8244            int flags) {
8245        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8246
8247        // reader
8248        synchronized (mPackages) {
8249            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8250            while (i.hasNext()) {
8251                final PackageParser.Instrumentation p = i.next();
8252                if (targetPackage == null
8253                        || targetPackage.equals(p.info.targetPackage)) {
8254                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8255                            flags);
8256                    if (ii != null) {
8257                        finalList.add(ii);
8258                    }
8259                }
8260            }
8261        }
8262
8263        return finalList;
8264    }
8265
8266    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8267        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8268        try {
8269            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8270        } finally {
8271            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8272        }
8273    }
8274
8275    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8276        final File[] files = scanDir.listFiles();
8277        if (ArrayUtils.isEmpty(files)) {
8278            Log.d(TAG, "No files in app dir " + scanDir);
8279            return;
8280        }
8281
8282        if (DEBUG_PACKAGE_SCANNING) {
8283            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8284                    + " flags=0x" + Integer.toHexString(parseFlags));
8285        }
8286        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8287                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8288                mParallelPackageParserCallback)) {
8289            // Submit files for parsing in parallel
8290            int fileCount = 0;
8291            for (File file : files) {
8292                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8293                        && !PackageInstallerService.isStageName(file.getName());
8294                if (!isPackage) {
8295                    // Ignore entries which are not packages
8296                    continue;
8297                }
8298                parallelPackageParser.submit(file, parseFlags);
8299                fileCount++;
8300            }
8301
8302            // Process results one by one
8303            for (; fileCount > 0; fileCount--) {
8304                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8305                Throwable throwable = parseResult.throwable;
8306                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8307
8308                if (throwable == null) {
8309                    // TODO(toddke): move lower in the scan chain
8310                    // Static shared libraries have synthetic package names
8311                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8312                        renameStaticSharedLibraryPackage(parseResult.pkg);
8313                    }
8314                    try {
8315                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8316                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8317                                    currentTime, null);
8318                        }
8319                    } catch (PackageManagerException e) {
8320                        errorCode = e.error;
8321                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8322                    }
8323                } else if (throwable instanceof PackageParser.PackageParserException) {
8324                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8325                            throwable;
8326                    errorCode = e.error;
8327                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8328                } else {
8329                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8330                            + parseResult.scanFile, throwable);
8331                }
8332
8333                // Delete invalid userdata apps
8334                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8335                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8336                    logCriticalInfo(Log.WARN,
8337                            "Deleting invalid package at " + parseResult.scanFile);
8338                    removeCodePathLI(parseResult.scanFile);
8339                }
8340            }
8341        }
8342    }
8343
8344    public static void reportSettingsProblem(int priority, String msg) {
8345        logCriticalInfo(priority, msg);
8346    }
8347
8348    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8349            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8350        // When upgrading from pre-N MR1, verify the package time stamp using the package
8351        // directory and not the APK file.
8352        final long lastModifiedTime = mIsPreNMR1Upgrade
8353                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8354        if (ps != null && !forceCollect
8355                && ps.codePathString.equals(pkg.codePath)
8356                && ps.timeStamp == lastModifiedTime
8357                && !isCompatSignatureUpdateNeeded(pkg)
8358                && !isRecoverSignatureUpdateNeeded(pkg)) {
8359            if (ps.signatures.mSigningDetails.signatures != null
8360                    && ps.signatures.mSigningDetails.signatures.length != 0
8361                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8362                            != SignatureSchemeVersion.UNKNOWN) {
8363                // Optimization: reuse the existing cached signing data
8364                // if the package appears to be unchanged.
8365                pkg.mSigningDetails =
8366                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8367                return;
8368            }
8369
8370            Slog.w(TAG, "PackageSetting for " + ps.name
8371                    + " is missing signatures.  Collecting certs again to recover them.");
8372        } else {
8373            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8374                    (forceCollect ? " (forced)" : ""));
8375        }
8376
8377        try {
8378            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8379            PackageParser.collectCertificates(pkg, skipVerify);
8380        } catch (PackageParserException e) {
8381            throw PackageManagerException.from(e);
8382        } finally {
8383            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8384        }
8385    }
8386
8387    /**
8388     *  Traces a package scan.
8389     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8390     */
8391    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8392            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8393        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8394        try {
8395            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8396        } finally {
8397            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8398        }
8399    }
8400
8401    /**
8402     *  Scans a package and returns the newly parsed package.
8403     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8404     */
8405    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8406            long currentTime, UserHandle user) throws PackageManagerException {
8407        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8408        PackageParser pp = new PackageParser();
8409        pp.setSeparateProcesses(mSeparateProcesses);
8410        pp.setOnlyCoreApps(mOnlyCore);
8411        pp.setDisplayMetrics(mMetrics);
8412        pp.setCallback(mPackageParserCallback);
8413
8414        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8415        final PackageParser.Package pkg;
8416        try {
8417            pkg = pp.parsePackage(scanFile, parseFlags);
8418        } catch (PackageParserException e) {
8419            throw PackageManagerException.from(e);
8420        } finally {
8421            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8422        }
8423
8424        // Static shared libraries have synthetic package names
8425        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8426            renameStaticSharedLibraryPackage(pkg);
8427        }
8428
8429        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8430    }
8431
8432    /**
8433     *  Scans a package and returns the newly parsed package.
8434     *  @throws PackageManagerException on a parse error.
8435     */
8436    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8437            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8438            @Nullable UserHandle user)
8439                    throws PackageManagerException {
8440        // If the package has children and this is the first dive in the function
8441        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8442        // packages (parent and children) would be successfully scanned before the
8443        // actual scan since scanning mutates internal state and we want to atomically
8444        // install the package and its children.
8445        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8446            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8447                scanFlags |= SCAN_CHECK_ONLY;
8448            }
8449        } else {
8450            scanFlags &= ~SCAN_CHECK_ONLY;
8451        }
8452
8453        // Scan the parent
8454        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8455                scanFlags, currentTime, user);
8456
8457        // Scan the children
8458        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8459        for (int i = 0; i < childCount; i++) {
8460            PackageParser.Package childPackage = pkg.childPackages.get(i);
8461            addForInitLI(childPackage, parseFlags, scanFlags,
8462                    currentTime, user);
8463        }
8464
8465
8466        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8467            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8468        }
8469
8470        return scannedPkg;
8471    }
8472
8473    /**
8474     * Returns if full apk verification can be skipped for the whole package, including the splits.
8475     */
8476    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8477        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8478            return false;
8479        }
8480        // TODO: Allow base and splits to be verified individually.
8481        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8482            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8483                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8484                    return false;
8485                }
8486            }
8487        }
8488        return true;
8489    }
8490
8491    /**
8492     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8493     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8494     * match one in a trusted source, and should be done separately.
8495     */
8496    private boolean canSkipFullApkVerification(String apkPath) {
8497        byte[] rootHashObserved = null;
8498        try {
8499            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8500            if (rootHashObserved == null) {
8501                return false;  // APK does not contain Merkle tree root hash.
8502            }
8503            synchronized (mInstallLock) {
8504                // Returns whether the observed root hash matches what kernel has.
8505                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8506                return true;
8507            }
8508        } catch (InstallerException | IOException | DigestException |
8509                NoSuchAlgorithmException e) {
8510            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8511        }
8512        return false;
8513    }
8514
8515    // Temporary to catch potential issues with refactoring
8516    private static boolean REFACTOR_DEBUG = true;
8517    /**
8518     * Adds a new package to the internal data structures during platform initialization.
8519     * <p>After adding, the package is known to the system and available for querying.
8520     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8521     * etc...], additional checks are performed. Basic verification [such as ensuring
8522     * matching signatures, checking version codes, etc...] occurs if the package is
8523     * identical to a previously known package. If the package fails a signature check,
8524     * the version installed on /data will be removed. If the version of the new package
8525     * is less than or equal than the version on /data, it will be ignored.
8526     * <p>Regardless of the package location, the results are applied to the internal
8527     * structures and the package is made available to the rest of the system.
8528     * <p>NOTE: The return value should be removed. It's the passed in package object.
8529     */
8530    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8531            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8532            @Nullable UserHandle user)
8533                    throws PackageManagerException {
8534        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8535        final String renamedPkgName;
8536        final PackageSetting disabledPkgSetting;
8537        final boolean isSystemPkgUpdated;
8538        final boolean pkgAlreadyExists;
8539        PackageSetting pkgSetting;
8540
8541        // NOTE: installPackageLI() has the same code to setup the package's
8542        // application info. This probably should be done lower in the call
8543        // stack [such as scanPackageOnly()]. However, we verify the application
8544        // info prior to that [in scanPackageNew()] and thus have to setup
8545        // the application info early.
8546        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8547        pkg.setApplicationInfoCodePath(pkg.codePath);
8548        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8549        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8550        pkg.setApplicationInfoResourcePath(pkg.codePath);
8551        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8552        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8553
8554        synchronized (mPackages) {
8555            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8556            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8557if (REFACTOR_DEBUG) {
8558Slog.e("TODD",
8559        "Add pkg: " + pkg.packageName + (realPkgName==null?"":", realName: " + realPkgName));
8560}
8561            if (realPkgName != null) {
8562                ensurePackageRenamed(pkg, renamedPkgName);
8563            }
8564            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8565            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8566            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8567            pkgAlreadyExists = pkgSetting != null;
8568            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8569            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8570            isSystemPkgUpdated = disabledPkgSetting != null;
8571
8572            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8573                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8574            }
8575if (REFACTOR_DEBUG) {
8576Slog.e("TODD",
8577        "SSP? " + scanSystemPartition
8578        + ", exists? " + pkgAlreadyExists + (pkgAlreadyExists?" "+pkgSetting.toString():"")
8579        + ", upgraded? " + isSystemPkgUpdated + (isSystemPkgUpdated?" "+disabledPkgSetting.toString():""));
8580}
8581
8582            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8583                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8584                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8585                    : null;
8586            if (DEBUG_PACKAGE_SCANNING
8587                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8588                    && sharedUserSetting != null) {
8589                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8590                        + " (uid=" + sharedUserSetting.userId + "):"
8591                        + " packages=" + sharedUserSetting.packages);
8592if (REFACTOR_DEBUG) {
8593Slog.e("TODD",
8594        "Shared UserID " + pkg.mSharedUserId
8595        + " (uid=" + sharedUserSetting.userId + "):"
8596        + " packages=" + sharedUserSetting.packages);
8597}
8598            }
8599
8600            if (scanSystemPartition) {
8601                // Potentially prune child packages. If the application on the /system
8602                // partition has been updated via OTA, but, is still disabled by a
8603                // version on /data, cycle through all of its children packages and
8604                // remove children that are no longer defined.
8605                if (isSystemPkgUpdated) {
8606if (REFACTOR_DEBUG) {
8607Slog.e("TODD",
8608        "Disable child packages");
8609}
8610                    final int scannedChildCount = (pkg.childPackages != null)
8611                            ? pkg.childPackages.size() : 0;
8612                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8613                            ? disabledPkgSetting.childPackageNames.size() : 0;
8614                    for (int i = 0; i < disabledChildCount; i++) {
8615                        String disabledChildPackageName =
8616                                disabledPkgSetting.childPackageNames.get(i);
8617                        boolean disabledPackageAvailable = false;
8618                        for (int j = 0; j < scannedChildCount; j++) {
8619                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8620                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8621if (REFACTOR_DEBUG) {
8622Slog.e("TODD",
8623        "Ignore " + disabledChildPackageName);
8624}
8625                                disabledPackageAvailable = true;
8626                                break;
8627                            }
8628                        }
8629                        if (!disabledPackageAvailable) {
8630if (REFACTOR_DEBUG) {
8631Slog.e("TODD",
8632        "Disable " + disabledChildPackageName);
8633}
8634                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8635                        }
8636                    }
8637                    // we're updating the disabled package, so, scan it as the package setting
8638                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8639                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8640                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8641                            (pkg == mPlatformPackage), user);
8642if (REFACTOR_DEBUG) {
8643Slog.e("TODD",
8644        "Scan disabled system package");
8645Slog.e("TODD",
8646        "Pre: " + request.pkgSetting.dumpState_temp());
8647}
8648final ScanResult result =
8649                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8650if (REFACTOR_DEBUG) {
8651Slog.e("TODD",
8652        "Post: " + (result.success?result.pkgSetting.dumpState_temp():"FAILED scan"));
8653}
8654                }
8655            }
8656        }
8657
8658        final boolean newPkgChangedPaths =
8659                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8660if (REFACTOR_DEBUG) {
8661Slog.e("TODD",
8662        "paths changed? " + newPkgChangedPaths
8663        + "; old: " + pkg.codePath
8664        + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.codePathString));
8665}
8666        final boolean newPkgVersionGreater =
8667                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8668if (REFACTOR_DEBUG) {
8669Slog.e("TODD",
8670        "version greater? " + newPkgVersionGreater
8671        + "; old: " + pkg.getLongVersionCode()
8672        + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.versionCode));
8673}
8674        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8675                && newPkgChangedPaths && newPkgVersionGreater;
8676if (REFACTOR_DEBUG) {
8677    Slog.e("TODD",
8678            "system better? " + isSystemPkgBetter);
8679}
8680        if (isSystemPkgBetter) {
8681            // The version of the application on /system is greater than the version on
8682            // /data. Switch back to the application on /system.
8683            // It's safe to assume the application on /system will correctly scan. If not,
8684            // there won't be a working copy of the application.
8685            synchronized (mPackages) {
8686                // just remove the loaded entries from package lists
8687                mPackages.remove(pkgSetting.name);
8688            }
8689
8690            logCriticalInfo(Log.WARN,
8691                    "System package updated;"
8692                    + " name: " + pkgSetting.name
8693                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8694                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8695if (REFACTOR_DEBUG) {
8696Slog.e("TODD",
8697        "System package changed;"
8698        + " name: " + pkgSetting.name
8699        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8700        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8701}
8702
8703            final InstallArgs args = createInstallArgsForExisting(
8704                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8705                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8706            args.cleanUpResourcesLI();
8707            synchronized (mPackages) {
8708                mSettings.enableSystemPackageLPw(pkgSetting.name);
8709            }
8710        }
8711
8712        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8713if (REFACTOR_DEBUG) {
8714Slog.e("TODD",
8715        "THROW exception; system pkg version not good enough");
8716}
8717            // The version of the application on the /system partition is less than or
8718            // equal to the version on the /data partition. Throw an exception and use
8719            // the application already installed on the /data partition.
8720            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8721                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8722                    + " better than this " + pkg.getLongVersionCode());
8723        }
8724
8725        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8726        // force re-collecting certificate.
8727        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8728                disabledPkgSetting);
8729        // Full APK verification can be skipped during certificate collection, only if the file is
8730        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8731        // cases, only data in Signing Block is verified instead of the whole file.
8732        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8733                (forceCollect && canSkipFullPackageVerification(pkg));
8734        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8735
8736        boolean shouldHideSystemApp = false;
8737        // A new application appeared on /system, but, we already have a copy of
8738        // the application installed on /data.
8739        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8740                && !pkgSetting.isSystem()) {
8741
8742            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8743                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8744                logCriticalInfo(Log.WARN,
8745                        "System package signature mismatch;"
8746                        + " name: " + pkgSetting.name);
8747if (REFACTOR_DEBUG) {
8748Slog.e("TODD",
8749        "System package signature mismatch;"
8750        + " name: " + pkgSetting.name);
8751}
8752                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8753                        "scanPackageInternalLI")) {
8754                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8755                }
8756                pkgSetting = null;
8757            } else if (newPkgVersionGreater) {
8758                // The application on /system is newer than the application on /data.
8759                // Simply remove the application on /data [keeping application data]
8760                // and replace it with the version on /system.
8761                logCriticalInfo(Log.WARN,
8762                        "System package enabled;"
8763                        + " name: " + pkgSetting.name
8764                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8765                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8766if (REFACTOR_DEBUG) {
8767Slog.e("TODD",
8768        "System package enabled;"
8769        + " name: " + pkgSetting.name
8770        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8771        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8772}
8773                InstallArgs args = createInstallArgsForExisting(
8774                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8775                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8776                synchronized (mInstallLock) {
8777                    args.cleanUpResourcesLI();
8778                }
8779            } else {
8780                // The application on /system is older than the application on /data. Hide
8781                // the application on /system and the version on /data will be scanned later
8782                // and re-added like an update.
8783                shouldHideSystemApp = true;
8784                logCriticalInfo(Log.INFO,
8785                        "System package disabled;"
8786                        + " name: " + pkgSetting.name
8787                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8788                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8789if (REFACTOR_DEBUG) {
8790Slog.e("TODD",
8791        "System package disabled;"
8792        + " name: " + pkgSetting.name
8793        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8794        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8795}
8796            }
8797        }
8798
8799if (REFACTOR_DEBUG) {
8800Slog.e("TODD",
8801        "Scan package");
8802Slog.e("TODD",
8803        "Pre: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp()));
8804}
8805        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8806                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8807if (REFACTOR_DEBUG) {
8808pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8809Slog.e("TODD",
8810        "Post: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp()));
8811}
8812
8813        if (shouldHideSystemApp) {
8814if (REFACTOR_DEBUG) {
8815Slog.e("TODD",
8816        "Disable package: " + pkg.packageName);
8817}
8818            synchronized (mPackages) {
8819                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8820            }
8821        }
8822        return scannedPkg;
8823    }
8824
8825    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8826        // Derive the new package synthetic package name
8827        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8828                + pkg.staticSharedLibVersion);
8829    }
8830
8831    private static String fixProcessName(String defProcessName,
8832            String processName) {
8833        if (processName == null) {
8834            return defProcessName;
8835        }
8836        return processName;
8837    }
8838
8839    /**
8840     * Enforces that only the system UID or root's UID can call a method exposed
8841     * via Binder.
8842     *
8843     * @param message used as message if SecurityException is thrown
8844     * @throws SecurityException if the caller is not system or root
8845     */
8846    private static final void enforceSystemOrRoot(String message) {
8847        final int uid = Binder.getCallingUid();
8848        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8849            throw new SecurityException(message);
8850        }
8851    }
8852
8853    @Override
8854    public void performFstrimIfNeeded() {
8855        enforceSystemOrRoot("Only the system can request fstrim");
8856
8857        // Before everything else, see whether we need to fstrim.
8858        try {
8859            IStorageManager sm = PackageHelper.getStorageManager();
8860            if (sm != null) {
8861                boolean doTrim = false;
8862                final long interval = android.provider.Settings.Global.getLong(
8863                        mContext.getContentResolver(),
8864                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8865                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8866                if (interval > 0) {
8867                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8868                    if (timeSinceLast > interval) {
8869                        doTrim = true;
8870                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8871                                + "; running immediately");
8872                    }
8873                }
8874                if (doTrim) {
8875                    final boolean dexOptDialogShown;
8876                    synchronized (mPackages) {
8877                        dexOptDialogShown = mDexOptDialogShown;
8878                    }
8879                    if (!isFirstBoot() && dexOptDialogShown) {
8880                        try {
8881                            ActivityManager.getService().showBootMessage(
8882                                    mContext.getResources().getString(
8883                                            R.string.android_upgrading_fstrim), true);
8884                        } catch (RemoteException e) {
8885                        }
8886                    }
8887                    sm.runMaintenance();
8888                }
8889            } else {
8890                Slog.e(TAG, "storageManager service unavailable!");
8891            }
8892        } catch (RemoteException e) {
8893            // Can't happen; StorageManagerService is local
8894        }
8895    }
8896
8897    @Override
8898    public void updatePackagesIfNeeded() {
8899        enforceSystemOrRoot("Only the system can request package update");
8900
8901        // We need to re-extract after an OTA.
8902        boolean causeUpgrade = isUpgrade();
8903
8904        // First boot or factory reset.
8905        // Note: we also handle devices that are upgrading to N right now as if it is their
8906        //       first boot, as they do not have profile data.
8907        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8908
8909        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8910        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8911
8912        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8913            return;
8914        }
8915
8916        List<PackageParser.Package> pkgs;
8917        synchronized (mPackages) {
8918            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8919        }
8920
8921        final long startTime = System.nanoTime();
8922        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8923                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8924                    false /* bootComplete */);
8925
8926        final int elapsedTimeSeconds =
8927                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8928
8929        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8930        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8931        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8932        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8933        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8934    }
8935
8936    /*
8937     * Return the prebuilt profile path given a package base code path.
8938     */
8939    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8940        return pkg.baseCodePath + ".prof";
8941    }
8942
8943    /**
8944     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8945     * containing statistics about the invocation. The array consists of three elements,
8946     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8947     * and {@code numberOfPackagesFailed}.
8948     */
8949    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8950            final String compilerFilter, boolean bootComplete) {
8951
8952        int numberOfPackagesVisited = 0;
8953        int numberOfPackagesOptimized = 0;
8954        int numberOfPackagesSkipped = 0;
8955        int numberOfPackagesFailed = 0;
8956        final int numberOfPackagesToDexopt = pkgs.size();
8957
8958        for (PackageParser.Package pkg : pkgs) {
8959            numberOfPackagesVisited++;
8960
8961            boolean useProfileForDexopt = false;
8962
8963            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8964                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8965                // that are already compiled.
8966                File profileFile = new File(getPrebuildProfilePath(pkg));
8967                // Copy profile if it exists.
8968                if (profileFile.exists()) {
8969                    try {
8970                        // We could also do this lazily before calling dexopt in
8971                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8972                        // is that we don't have a good way to say "do this only once".
8973                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8974                                pkg.applicationInfo.uid, pkg.packageName,
8975                                ArtManager.getProfileName(null))) {
8976                            Log.e(TAG, "Installer failed to copy system profile!");
8977                        } else {
8978                            // Disabled as this causes speed-profile compilation during first boot
8979                            // even if things are already compiled.
8980                            // useProfileForDexopt = true;
8981                        }
8982                    } catch (Exception e) {
8983                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8984                                e);
8985                    }
8986                } else {
8987                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8988                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8989                    // minimize the number off apps being speed-profile compiled during first boot.
8990                    // The other paths will not change the filter.
8991                    if (disabledPs != null && disabledPs.pkg.isStub) {
8992                        // The package is the stub one, remove the stub suffix to get the normal
8993                        // package and APK names.
8994                        String systemProfilePath =
8995                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8996                        profileFile = new File(systemProfilePath);
8997                        // If we have a profile for a compressed APK, copy it to the reference
8998                        // location.
8999                        // Note that copying the profile here will cause it to override the
9000                        // reference profile every OTA even though the existing reference profile
9001                        // may have more data. We can't copy during decompression since the
9002                        // directories are not set up at that point.
9003                        if (profileFile.exists()) {
9004                            try {
9005                                // We could also do this lazily before calling dexopt in
9006                                // PackageDexOptimizer to prevent this happening on first boot. The
9007                                // issue is that we don't have a good way to say "do this only
9008                                // once".
9009                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9010                                        pkg.applicationInfo.uid, pkg.packageName,
9011                                        ArtManager.getProfileName(null))) {
9012                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9013                                } else {
9014                                    useProfileForDexopt = true;
9015                                }
9016                            } catch (Exception e) {
9017                                Log.e(TAG, "Failed to copy profile " +
9018                                        profileFile.getAbsolutePath() + " ", e);
9019                            }
9020                        }
9021                    }
9022                }
9023            }
9024
9025            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9026                if (DEBUG_DEXOPT) {
9027                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9028                }
9029                numberOfPackagesSkipped++;
9030                continue;
9031            }
9032
9033            if (DEBUG_DEXOPT) {
9034                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9035                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9036            }
9037
9038            if (showDialog) {
9039                try {
9040                    ActivityManager.getService().showBootMessage(
9041                            mContext.getResources().getString(R.string.android_upgrading_apk,
9042                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9043                } catch (RemoteException e) {
9044                }
9045                synchronized (mPackages) {
9046                    mDexOptDialogShown = true;
9047                }
9048            }
9049
9050            String pkgCompilerFilter = compilerFilter;
9051            if (useProfileForDexopt) {
9052                // Use background dexopt mode to try and use the profile. Note that this does not
9053                // guarantee usage of the profile.
9054                pkgCompilerFilter =
9055                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9056                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9057            }
9058
9059            // checkProfiles is false to avoid merging profiles during boot which
9060            // might interfere with background compilation (b/28612421).
9061            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9062            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9063            // trade-off worth doing to save boot time work.
9064            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9065            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9066                    pkg.packageName,
9067                    pkgCompilerFilter,
9068                    dexoptFlags));
9069
9070            switch (primaryDexOptStaus) {
9071                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9072                    numberOfPackagesOptimized++;
9073                    break;
9074                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9075                    numberOfPackagesSkipped++;
9076                    break;
9077                case PackageDexOptimizer.DEX_OPT_FAILED:
9078                    numberOfPackagesFailed++;
9079                    break;
9080                default:
9081                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9082                    break;
9083            }
9084        }
9085
9086        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9087                numberOfPackagesFailed };
9088    }
9089
9090    @Override
9091    public void notifyPackageUse(String packageName, int reason) {
9092        synchronized (mPackages) {
9093            final int callingUid = Binder.getCallingUid();
9094            final int callingUserId = UserHandle.getUserId(callingUid);
9095            if (getInstantAppPackageName(callingUid) != null) {
9096                if (!isCallerSameApp(packageName, callingUid)) {
9097                    return;
9098                }
9099            } else {
9100                if (isInstantApp(packageName, callingUserId)) {
9101                    return;
9102                }
9103            }
9104            notifyPackageUseLocked(packageName, reason);
9105        }
9106    }
9107
9108    private void notifyPackageUseLocked(String packageName, int reason) {
9109        final PackageParser.Package p = mPackages.get(packageName);
9110        if (p == null) {
9111            return;
9112        }
9113        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9114    }
9115
9116    @Override
9117    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9118            List<String> classPaths, String loaderIsa) {
9119        int userId = UserHandle.getCallingUserId();
9120        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9121        if (ai == null) {
9122            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9123                + loadingPackageName + ", user=" + userId);
9124            return;
9125        }
9126        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9127    }
9128
9129    @Override
9130    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9131            IDexModuleRegisterCallback callback) {
9132        int userId = UserHandle.getCallingUserId();
9133        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9134        DexManager.RegisterDexModuleResult result;
9135        if (ai == null) {
9136            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9137                     " calling user. package=" + packageName + ", user=" + userId);
9138            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9139        } else {
9140            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9141        }
9142
9143        if (callback != null) {
9144            mHandler.post(() -> {
9145                try {
9146                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9147                } catch (RemoteException e) {
9148                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9149                }
9150            });
9151        }
9152    }
9153
9154    /**
9155     * Ask the package manager to perform a dex-opt with the given compiler filter.
9156     *
9157     * Note: exposed only for the shell command to allow moving packages explicitly to a
9158     *       definite state.
9159     */
9160    @Override
9161    public boolean performDexOptMode(String packageName,
9162            boolean checkProfiles, String targetCompilerFilter, boolean force,
9163            boolean bootComplete, String splitName) {
9164        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9165                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9166                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9167        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9168                splitName, flags));
9169    }
9170
9171    /**
9172     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9173     * secondary dex files belonging to the given package.
9174     *
9175     * Note: exposed only for the shell command to allow moving packages explicitly to a
9176     *       definite state.
9177     */
9178    @Override
9179    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9180            boolean force) {
9181        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9182                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9183                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9184                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9185        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9186    }
9187
9188    /*package*/ boolean performDexOpt(DexoptOptions options) {
9189        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9190            return false;
9191        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9192            return false;
9193        }
9194
9195        if (options.isDexoptOnlySecondaryDex()) {
9196            return mDexManager.dexoptSecondaryDex(options);
9197        } else {
9198            int dexoptStatus = performDexOptWithStatus(options);
9199            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9200        }
9201    }
9202
9203    /**
9204     * Perform dexopt on the given package and return one of following result:
9205     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9206     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9207     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9208     */
9209    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9210        return performDexOptTraced(options);
9211    }
9212
9213    private int performDexOptTraced(DexoptOptions options) {
9214        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9215        try {
9216            return performDexOptInternal(options);
9217        } finally {
9218            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9219        }
9220    }
9221
9222    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9223    // if the package can now be considered up to date for the given filter.
9224    private int performDexOptInternal(DexoptOptions options) {
9225        PackageParser.Package p;
9226        synchronized (mPackages) {
9227            p = mPackages.get(options.getPackageName());
9228            if (p == null) {
9229                // Package could not be found. Report failure.
9230                return PackageDexOptimizer.DEX_OPT_FAILED;
9231            }
9232            mPackageUsage.maybeWriteAsync(mPackages);
9233            mCompilerStats.maybeWriteAsync();
9234        }
9235        long callingId = Binder.clearCallingIdentity();
9236        try {
9237            synchronized (mInstallLock) {
9238                return performDexOptInternalWithDependenciesLI(p, options);
9239            }
9240        } finally {
9241            Binder.restoreCallingIdentity(callingId);
9242        }
9243    }
9244
9245    public ArraySet<String> getOptimizablePackages() {
9246        ArraySet<String> pkgs = new ArraySet<String>();
9247        synchronized (mPackages) {
9248            for (PackageParser.Package p : mPackages.values()) {
9249                if (PackageDexOptimizer.canOptimizePackage(p)) {
9250                    pkgs.add(p.packageName);
9251                }
9252            }
9253        }
9254        return pkgs;
9255    }
9256
9257    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9258            DexoptOptions options) {
9259        // Select the dex optimizer based on the force parameter.
9260        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9261        //       allocate an object here.
9262        PackageDexOptimizer pdo = options.isForce()
9263                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9264                : mPackageDexOptimizer;
9265
9266        // Dexopt all dependencies first. Note: we ignore the return value and march on
9267        // on errors.
9268        // Note that we are going to call performDexOpt on those libraries as many times as
9269        // they are referenced in packages. When we do a batch of performDexOpt (for example
9270        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9271        // and the first package that uses the library will dexopt it. The
9272        // others will see that the compiled code for the library is up to date.
9273        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9274        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9275        if (!deps.isEmpty()) {
9276            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9277                    options.getCompilerFilter(), options.getSplitName(),
9278                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9279            for (PackageParser.Package depPackage : deps) {
9280                // TODO: Analyze and investigate if we (should) profile libraries.
9281                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9282                        getOrCreateCompilerPackageStats(depPackage),
9283                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9284            }
9285        }
9286        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9287                getOrCreateCompilerPackageStats(p),
9288                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9289    }
9290
9291    /**
9292     * Reconcile the information we have about the secondary dex files belonging to
9293     * {@code packagName} and the actual dex files. For all dex files that were
9294     * deleted, update the internal records and delete the generated oat files.
9295     */
9296    @Override
9297    public void reconcileSecondaryDexFiles(String packageName) {
9298        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9299            return;
9300        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9301            return;
9302        }
9303        mDexManager.reconcileSecondaryDexFiles(packageName);
9304    }
9305
9306    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9307    // a reference there.
9308    /*package*/ DexManager getDexManager() {
9309        return mDexManager;
9310    }
9311
9312    /**
9313     * Execute the background dexopt job immediately.
9314     */
9315    @Override
9316    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9317        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9318            return false;
9319        }
9320        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9321    }
9322
9323    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9324        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9325                || p.usesStaticLibraries != null) {
9326            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9327            Set<String> collectedNames = new HashSet<>();
9328            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9329
9330            retValue.remove(p);
9331
9332            return retValue;
9333        } else {
9334            return Collections.emptyList();
9335        }
9336    }
9337
9338    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9339            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9340        if (!collectedNames.contains(p.packageName)) {
9341            collectedNames.add(p.packageName);
9342            collected.add(p);
9343
9344            if (p.usesLibraries != null) {
9345                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9346                        null, collected, collectedNames);
9347            }
9348            if (p.usesOptionalLibraries != null) {
9349                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9350                        null, collected, collectedNames);
9351            }
9352            if (p.usesStaticLibraries != null) {
9353                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9354                        p.usesStaticLibrariesVersions, collected, collectedNames);
9355            }
9356        }
9357    }
9358
9359    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9360            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9361        final int libNameCount = libs.size();
9362        for (int i = 0; i < libNameCount; i++) {
9363            String libName = libs.get(i);
9364            long version = (versions != null && versions.length == libNameCount)
9365                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9366            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9367            if (libPkg != null) {
9368                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9369            }
9370        }
9371    }
9372
9373    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9374        synchronized (mPackages) {
9375            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9376            if (libEntry != null) {
9377                return mPackages.get(libEntry.apk);
9378            }
9379            return null;
9380        }
9381    }
9382
9383    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9384        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9385        if (versionedLib == null) {
9386            return null;
9387        }
9388        return versionedLib.get(version);
9389    }
9390
9391    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9392        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9393                pkg.staticSharedLibName);
9394        if (versionedLib == null) {
9395            return null;
9396        }
9397        long previousLibVersion = -1;
9398        final int versionCount = versionedLib.size();
9399        for (int i = 0; i < versionCount; i++) {
9400            final long libVersion = versionedLib.keyAt(i);
9401            if (libVersion < pkg.staticSharedLibVersion) {
9402                previousLibVersion = Math.max(previousLibVersion, libVersion);
9403            }
9404        }
9405        if (previousLibVersion >= 0) {
9406            return versionedLib.get(previousLibVersion);
9407        }
9408        return null;
9409    }
9410
9411    public void shutdown() {
9412        mPackageUsage.writeNow(mPackages);
9413        mCompilerStats.writeNow();
9414        mDexManager.writePackageDexUsageNow();
9415    }
9416
9417    @Override
9418    public void dumpProfiles(String packageName) {
9419        PackageParser.Package pkg;
9420        synchronized (mPackages) {
9421            pkg = mPackages.get(packageName);
9422            if (pkg == null) {
9423                throw new IllegalArgumentException("Unknown package: " + packageName);
9424            }
9425        }
9426        /* Only the shell, root, or the app user should be able to dump profiles. */
9427        int callingUid = Binder.getCallingUid();
9428        if (callingUid != Process.SHELL_UID &&
9429            callingUid != Process.ROOT_UID &&
9430            callingUid != pkg.applicationInfo.uid) {
9431            throw new SecurityException("dumpProfiles");
9432        }
9433
9434        synchronized (mInstallLock) {
9435            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9436            mArtManagerService.dumpProfiles(pkg);
9437            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9438        }
9439    }
9440
9441    @Override
9442    public void forceDexOpt(String packageName) {
9443        enforceSystemOrRoot("forceDexOpt");
9444
9445        PackageParser.Package pkg;
9446        synchronized (mPackages) {
9447            pkg = mPackages.get(packageName);
9448            if (pkg == null) {
9449                throw new IllegalArgumentException("Unknown package: " + packageName);
9450            }
9451        }
9452
9453        synchronized (mInstallLock) {
9454            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9455
9456            // Whoever is calling forceDexOpt wants a compiled package.
9457            // Don't use profiles since that may cause compilation to be skipped.
9458            final int res = performDexOptInternalWithDependenciesLI(
9459                    pkg,
9460                    new DexoptOptions(packageName,
9461                            getDefaultCompilerFilter(),
9462                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9463
9464            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9465            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9466                throw new IllegalStateException("Failed to dexopt: " + res);
9467            }
9468        }
9469    }
9470
9471    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9472        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9473            Slog.w(TAG, "Unable to update from " + oldPkg.name
9474                    + " to " + newPkg.packageName
9475                    + ": old package not in system partition");
9476            return false;
9477        } else if (mPackages.get(oldPkg.name) != null) {
9478            Slog.w(TAG, "Unable to update from " + oldPkg.name
9479                    + " to " + newPkg.packageName
9480                    + ": old package still exists");
9481            return false;
9482        }
9483        return true;
9484    }
9485
9486    void removeCodePathLI(File codePath) {
9487        if (codePath.isDirectory()) {
9488            try {
9489                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9490            } catch (InstallerException e) {
9491                Slog.w(TAG, "Failed to remove code path", e);
9492            }
9493        } else {
9494            codePath.delete();
9495        }
9496    }
9497
9498    private int[] resolveUserIds(int userId) {
9499        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9500    }
9501
9502    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9503        if (pkg == null) {
9504            Slog.wtf(TAG, "Package was null!", new Throwable());
9505            return;
9506        }
9507        clearAppDataLeafLIF(pkg, userId, flags);
9508        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9509        for (int i = 0; i < childCount; i++) {
9510            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9511        }
9512
9513        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9514    }
9515
9516    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9517        final PackageSetting ps;
9518        synchronized (mPackages) {
9519            ps = mSettings.mPackages.get(pkg.packageName);
9520        }
9521        for (int realUserId : resolveUserIds(userId)) {
9522            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9523            try {
9524                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9525                        ceDataInode);
9526            } catch (InstallerException e) {
9527                Slog.w(TAG, String.valueOf(e));
9528            }
9529        }
9530    }
9531
9532    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9533        if (pkg == null) {
9534            Slog.wtf(TAG, "Package was null!", new Throwable());
9535            return;
9536        }
9537        destroyAppDataLeafLIF(pkg, userId, flags);
9538        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9539        for (int i = 0; i < childCount; i++) {
9540            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9541        }
9542    }
9543
9544    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9545        final PackageSetting ps;
9546        synchronized (mPackages) {
9547            ps = mSettings.mPackages.get(pkg.packageName);
9548        }
9549        for (int realUserId : resolveUserIds(userId)) {
9550            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9551            try {
9552                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9553                        ceDataInode);
9554            } catch (InstallerException e) {
9555                Slog.w(TAG, String.valueOf(e));
9556            }
9557            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9558        }
9559    }
9560
9561    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9562        if (pkg == null) {
9563            Slog.wtf(TAG, "Package was null!", new Throwable());
9564            return;
9565        }
9566        destroyAppProfilesLeafLIF(pkg);
9567        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9568        for (int i = 0; i < childCount; i++) {
9569            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9570        }
9571    }
9572
9573    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9574        try {
9575            mInstaller.destroyAppProfiles(pkg.packageName);
9576        } catch (InstallerException e) {
9577            Slog.w(TAG, String.valueOf(e));
9578        }
9579    }
9580
9581    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9582        if (pkg == null) {
9583            Slog.wtf(TAG, "Package was null!", new Throwable());
9584            return;
9585        }
9586        mArtManagerService.clearAppProfiles(pkg);
9587        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9588        for (int i = 0; i < childCount; i++) {
9589            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9590        }
9591    }
9592
9593    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9594            long lastUpdateTime) {
9595        // Set parent install/update time
9596        PackageSetting ps = (PackageSetting) pkg.mExtras;
9597        if (ps != null) {
9598            ps.firstInstallTime = firstInstallTime;
9599            ps.lastUpdateTime = lastUpdateTime;
9600        }
9601        // Set children install/update time
9602        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9603        for (int i = 0; i < childCount; i++) {
9604            PackageParser.Package childPkg = pkg.childPackages.get(i);
9605            ps = (PackageSetting) childPkg.mExtras;
9606            if (ps != null) {
9607                ps.firstInstallTime = firstInstallTime;
9608                ps.lastUpdateTime = lastUpdateTime;
9609            }
9610        }
9611    }
9612
9613    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9614            SharedLibraryEntry file,
9615            PackageParser.Package changingLib) {
9616        if (file.path != null) {
9617            usesLibraryFiles.add(file.path);
9618            return;
9619        }
9620        PackageParser.Package p = mPackages.get(file.apk);
9621        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9622            // If we are doing this while in the middle of updating a library apk,
9623            // then we need to make sure to use that new apk for determining the
9624            // dependencies here.  (We haven't yet finished committing the new apk
9625            // to the package manager state.)
9626            if (p == null || p.packageName.equals(changingLib.packageName)) {
9627                p = changingLib;
9628            }
9629        }
9630        if (p != null) {
9631            usesLibraryFiles.addAll(p.getAllCodePaths());
9632            if (p.usesLibraryFiles != null) {
9633                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9634            }
9635        }
9636    }
9637
9638    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9639            PackageParser.Package changingLib) throws PackageManagerException {
9640        if (pkg == null) {
9641            return;
9642        }
9643        // The collection used here must maintain the order of addition (so
9644        // that libraries are searched in the correct order) and must have no
9645        // duplicates.
9646        Set<String> usesLibraryFiles = null;
9647        if (pkg.usesLibraries != null) {
9648            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9649                    null, null, pkg.packageName, changingLib, true,
9650                    pkg.applicationInfo.targetSdkVersion, null);
9651        }
9652        if (pkg.usesStaticLibraries != null) {
9653            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9654                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9655                    pkg.packageName, changingLib, true,
9656                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9657        }
9658        if (pkg.usesOptionalLibraries != null) {
9659            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9660                    null, null, pkg.packageName, changingLib, false,
9661                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9662        }
9663        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9664            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9665        } else {
9666            pkg.usesLibraryFiles = null;
9667        }
9668    }
9669
9670    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9671            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9672            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9673            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9674            throws PackageManagerException {
9675        final int libCount = requestedLibraries.size();
9676        for (int i = 0; i < libCount; i++) {
9677            final String libName = requestedLibraries.get(i);
9678            final long libVersion = requiredVersions != null ? requiredVersions[i]
9679                    : SharedLibraryInfo.VERSION_UNDEFINED;
9680            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9681            if (libEntry == null) {
9682                if (required) {
9683                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9684                            "Package " + packageName + " requires unavailable shared library "
9685                                    + libName + "; failing!");
9686                } else if (DEBUG_SHARED_LIBRARIES) {
9687                    Slog.i(TAG, "Package " + packageName
9688                            + " desires unavailable shared library "
9689                            + libName + "; ignoring!");
9690                }
9691            } else {
9692                if (requiredVersions != null && requiredCertDigests != null) {
9693                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9694                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9695                            "Package " + packageName + " requires unavailable static shared"
9696                                    + " library " + libName + " version "
9697                                    + libEntry.info.getLongVersion() + "; failing!");
9698                    }
9699
9700                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9701                    if (libPkg == null) {
9702                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9703                                "Package " + packageName + " requires unavailable static shared"
9704                                        + " library; failing!");
9705                    }
9706
9707                    final String[] expectedCertDigests = requiredCertDigests[i];
9708
9709
9710                    if (expectedCertDigests.length > 1) {
9711
9712                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9713                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9714                                ? PackageUtils.computeSignaturesSha256Digests(
9715                                libPkg.mSigningDetails.signatures)
9716                                : PackageUtils.computeSignaturesSha256Digests(
9717                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9718
9719                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9720                        // target O we don't parse the "additional-certificate" tags similarly
9721                        // how we only consider all certs only for apps targeting O (see above).
9722                        // Therefore, the size check is safe to make.
9723                        if (expectedCertDigests.length != libCertDigests.length) {
9724                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9725                                    "Package " + packageName + " requires differently signed" +
9726                                            " static shared library; failing!");
9727                        }
9728
9729                        // Use a predictable order as signature order may vary
9730                        Arrays.sort(libCertDigests);
9731                        Arrays.sort(expectedCertDigests);
9732
9733                        final int certCount = libCertDigests.length;
9734                        for (int j = 0; j < certCount; j++) {
9735                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9736                                throw new PackageManagerException(
9737                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9738                                        "Package " + packageName + " requires differently signed" +
9739                                                " static shared library; failing!");
9740                            }
9741                        }
9742                    } else {
9743
9744                        // lib signing cert could have rotated beyond the one expected, check to see
9745                        // if the new one has been blessed by the old
9746                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9747                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9748                            throw new PackageManagerException(
9749                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9750                                    "Package " + packageName + " requires differently signed" +
9751                                            " static shared library; failing!");
9752                        }
9753                    }
9754                }
9755
9756                if (outUsedLibraries == null) {
9757                    // Use LinkedHashSet to preserve the order of files added to
9758                    // usesLibraryFiles while eliminating duplicates.
9759                    outUsedLibraries = new LinkedHashSet<>();
9760                }
9761                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9762            }
9763        }
9764        return outUsedLibraries;
9765    }
9766
9767    private static boolean hasString(List<String> list, List<String> which) {
9768        if (list == null) {
9769            return false;
9770        }
9771        for (int i=list.size()-1; i>=0; i--) {
9772            for (int j=which.size()-1; j>=0; j--) {
9773                if (which.get(j).equals(list.get(i))) {
9774                    return true;
9775                }
9776            }
9777        }
9778        return false;
9779    }
9780
9781    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9782            PackageParser.Package changingPkg) {
9783        ArrayList<PackageParser.Package> res = null;
9784        for (PackageParser.Package pkg : mPackages.values()) {
9785            if (changingPkg != null
9786                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9787                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9788                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9789                            changingPkg.staticSharedLibName)) {
9790                return null;
9791            }
9792            if (res == null) {
9793                res = new ArrayList<>();
9794            }
9795            res.add(pkg);
9796            try {
9797                updateSharedLibrariesLPr(pkg, changingPkg);
9798            } catch (PackageManagerException e) {
9799                // If a system app update or an app and a required lib missing we
9800                // delete the package and for updated system apps keep the data as
9801                // it is better for the user to reinstall than to be in an limbo
9802                // state. Also libs disappearing under an app should never happen
9803                // - just in case.
9804                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9805                    final int flags = pkg.isUpdatedSystemApp()
9806                            ? PackageManager.DELETE_KEEP_DATA : 0;
9807                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9808                            flags , null, true, null);
9809                }
9810                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9811            }
9812        }
9813        return res;
9814    }
9815
9816    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9817            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9818            @Nullable UserHandle user) throws PackageManagerException {
9819        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9820        // If the package has children and this is the first dive in the function
9821        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9822        // whether all packages (parent and children) would be successfully scanned
9823        // before the actual scan since scanning mutates internal state and we want
9824        // to atomically install the package and its children.
9825        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9826            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9827                scanFlags |= SCAN_CHECK_ONLY;
9828            }
9829        } else {
9830            scanFlags &= ~SCAN_CHECK_ONLY;
9831        }
9832
9833        final PackageParser.Package scannedPkg;
9834        try {
9835            // Scan the parent
9836            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9837            // Scan the children
9838            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9839            for (int i = 0; i < childCount; i++) {
9840                PackageParser.Package childPkg = pkg.childPackages.get(i);
9841                scanPackageNewLI(childPkg, parseFlags,
9842                        scanFlags, currentTime, user);
9843            }
9844        } finally {
9845            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9846        }
9847
9848        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9849            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9850        }
9851
9852        return scannedPkg;
9853    }
9854
9855    /** The result of a package scan. */
9856    private static class ScanResult {
9857        /** Whether or not the package scan was successful */
9858        public final boolean success;
9859        /**
9860         * The final package settings. This may be the same object passed in
9861         * the {@link ScanRequest}, but, with modified values.
9862         */
9863        @Nullable public final PackageSetting pkgSetting;
9864        /** ABI code paths that have changed in the package scan */
9865        @Nullable public final List<String> changedAbiCodePath;
9866        public ScanResult(
9867                boolean success,
9868                @Nullable PackageSetting pkgSetting,
9869                @Nullable List<String> changedAbiCodePath) {
9870            this.success = success;
9871            this.pkgSetting = pkgSetting;
9872            this.changedAbiCodePath = changedAbiCodePath;
9873        }
9874    }
9875
9876    /** A package to be scanned */
9877    private static class ScanRequest {
9878        /** The parsed package */
9879        @NonNull public final PackageParser.Package pkg;
9880        /** Shared user settings, if the package has a shared user */
9881        @Nullable public final SharedUserSetting sharedUserSetting;
9882        /**
9883         * Package settings of the currently installed version.
9884         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9885         * during scan.
9886         */
9887        @Nullable public final PackageSetting pkgSetting;
9888        /** A copy of the settings for the currently installed version */
9889        @Nullable public final PackageSetting oldPkgSetting;
9890        /** Package settings for the disabled version on the /system partition */
9891        @Nullable public final PackageSetting disabledPkgSetting;
9892        /** Package settings for the installed version under its original package name */
9893        @Nullable public final PackageSetting originalPkgSetting;
9894        /** The real package name of a renamed application */
9895        @Nullable public final String realPkgName;
9896        public final @ParseFlags int parseFlags;
9897        public final @ScanFlags int scanFlags;
9898        /** The user for which the package is being scanned */
9899        @Nullable public final UserHandle user;
9900        /** Whether or not the platform package is being scanned */
9901        public final boolean isPlatformPackage;
9902        public ScanRequest(
9903                @NonNull PackageParser.Package pkg,
9904                @Nullable SharedUserSetting sharedUserSetting,
9905                @Nullable PackageSetting pkgSetting,
9906                @Nullable PackageSetting disabledPkgSetting,
9907                @Nullable PackageSetting originalPkgSetting,
9908                @Nullable String realPkgName,
9909                @ParseFlags int parseFlags,
9910                @ScanFlags int scanFlags,
9911                boolean isPlatformPackage,
9912                @Nullable UserHandle user) {
9913            this.pkg = pkg;
9914            this.pkgSetting = pkgSetting;
9915            this.sharedUserSetting = sharedUserSetting;
9916            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9917            this.disabledPkgSetting = disabledPkgSetting;
9918            this.originalPkgSetting = originalPkgSetting;
9919            this.realPkgName = realPkgName;
9920            this.parseFlags = parseFlags;
9921            this.scanFlags = scanFlags;
9922            this.isPlatformPackage = isPlatformPackage;
9923            this.user = user;
9924        }
9925    }
9926
9927    /**
9928     * Returns the actual scan flags depending upon the state of the other settings.
9929     * <p>Updated system applications will not have the following flags set
9930     * by default and need to be adjusted after the fact:
9931     * <ul>
9932     * <li>{@link #SCAN_AS_SYSTEM}</li>
9933     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9934     * <li>{@link #SCAN_AS_OEM}</li>
9935     * <li>{@link #SCAN_AS_VENDOR}</li>
9936     * <li>{@link #SCAN_AS_PRODUCT}</li>
9937     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9938     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9939     * </ul>
9940     */
9941    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9942            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9943            PackageParser.Package pkg) {
9944        if (disabledPkgSetting != null) {
9945            // updated system application, must at least have SCAN_AS_SYSTEM
9946            scanFlags |= SCAN_AS_SYSTEM;
9947            if ((disabledPkgSetting.pkgPrivateFlags
9948                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9949                scanFlags |= SCAN_AS_PRIVILEGED;
9950            }
9951            if ((disabledPkgSetting.pkgPrivateFlags
9952                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9953                scanFlags |= SCAN_AS_OEM;
9954            }
9955            if ((disabledPkgSetting.pkgPrivateFlags
9956                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9957                scanFlags |= SCAN_AS_VENDOR;
9958            }
9959            if ((disabledPkgSetting.pkgPrivateFlags
9960                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9961                scanFlags |= SCAN_AS_PRODUCT;
9962            }
9963        }
9964        if (pkgSetting != null) {
9965            final int userId = ((user == null) ? 0 : user.getIdentifier());
9966            if (pkgSetting.getInstantApp(userId)) {
9967                scanFlags |= SCAN_AS_INSTANT_APP;
9968            }
9969            if (pkgSetting.getVirtulalPreload(userId)) {
9970                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9971            }
9972        }
9973
9974        // Scan as privileged apps that share a user with a priv-app.
9975        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9976                && (pkg.mSharedUserId != null)) {
9977            SharedUserSetting sharedUserSetting = null;
9978            try {
9979                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9980            } catch (PackageManagerException ignore) {}
9981            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9982                // Exempt SharedUsers signed with the platform key.
9983                // TODO(b/72378145) Fix this exemption. Force signature apps
9984                // to whitelist their privileged permissions just like other
9985                // priv-apps.
9986                synchronized (mPackages) {
9987                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9988                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9989                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9990                        scanFlags |= SCAN_AS_PRIVILEGED;
9991                    }
9992                }
9993            }
9994        }
9995
9996        return scanFlags;
9997    }
9998
9999    @GuardedBy("mInstallLock")
10000    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10001            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10002            @Nullable UserHandle user) throws PackageManagerException {
10003
10004        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10005        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10006        if (realPkgName != null) {
10007            ensurePackageRenamed(pkg, renamedPkgName);
10008        }
10009        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10010        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10011        final PackageSetting disabledPkgSetting =
10012                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10013
10014        if (mTransferedPackages.contains(pkg.packageName)) {
10015            Slog.w(TAG, "Package " + pkg.packageName
10016                    + " was transferred to another, but its .apk remains");
10017        }
10018
10019        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10020        synchronized (mPackages) {
10021            applyPolicy(pkg, parseFlags, scanFlags);
10022            assertPackageIsValid(pkg, parseFlags, scanFlags);
10023
10024            SharedUserSetting sharedUserSetting = null;
10025            if (pkg.mSharedUserId != null) {
10026                // SIDE EFFECTS; may potentially allocate a new shared user
10027                sharedUserSetting = mSettings.getSharedUserLPw(
10028                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10029                if (DEBUG_PACKAGE_SCANNING) {
10030                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10031                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10032                                + " (uid=" + sharedUserSetting.userId + "):"
10033                                + " packages=" + sharedUserSetting.packages);
10034                }
10035            }
10036
10037            boolean scanSucceeded = false;
10038            try {
10039                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
10040                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
10041                        (pkg == mPlatformPackage), user);
10042                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10043                if (result.success) {
10044                    commitScanResultsLocked(request, result);
10045                }
10046                scanSucceeded = true;
10047            } finally {
10048                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10049                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10050                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10051                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10052                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10053                  }
10054            }
10055        }
10056        return pkg;
10057    }
10058
10059    /**
10060     * Commits the package scan and modifies system state.
10061     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10062     * of committing the package, leaving the system in an inconsistent state.
10063     * This needs to be fixed so, once we get to this point, no errors are
10064     * possible and the system is not left in an inconsistent state.
10065     */
10066    @GuardedBy("mPackages")
10067    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10068            throws PackageManagerException {
10069        final PackageParser.Package pkg = request.pkg;
10070        final @ParseFlags int parseFlags = request.parseFlags;
10071        final @ScanFlags int scanFlags = request.scanFlags;
10072        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10073        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10074        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10075        final UserHandle user = request.user;
10076        final String realPkgName = request.realPkgName;
10077        final PackageSetting pkgSetting = result.pkgSetting;
10078        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10079        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10080
10081        if (newPkgSettingCreated) {
10082            if (originalPkgSetting != null) {
10083                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10084            }
10085            // THROWS: when we can't allocate a user id. add call to check if there's
10086            // enough space to ensure we won't throw; otherwise, don't modify state
10087            mSettings.addUserToSettingLPw(pkgSetting);
10088
10089            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10090                mTransferedPackages.add(originalPkgSetting.name);
10091            }
10092        }
10093        // TODO(toddke): Consider a method specifically for modifying the Package object
10094        // post scan; or, moving this stuff out of the Package object since it has nothing
10095        // to do with the package on disk.
10096        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10097        // for creating the application ID. If we did this earlier, we would be saving the
10098        // correct ID.
10099        pkg.applicationInfo.uid = pkgSetting.appId;
10100
10101        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10102
10103        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10104            mTransferedPackages.add(pkg.packageName);
10105        }
10106
10107        // THROWS: when requested libraries that can't be found. it only changes
10108        // the state of the passed in pkg object, so, move to the top of the method
10109        // and allow it to abort
10110        if ((scanFlags & SCAN_BOOTING) == 0
10111                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10112            // Check all shared libraries and map to their actual file path.
10113            // We only do this here for apps not on a system dir, because those
10114            // are the only ones that can fail an install due to this.  We
10115            // will take care of the system apps by updating all of their
10116            // library paths after the scan is done. Also during the initial
10117            // scan don't update any libs as we do this wholesale after all
10118            // apps are scanned to avoid dependency based scanning.
10119            updateSharedLibrariesLPr(pkg, null);
10120        }
10121
10122        // All versions of a static shared library are referenced with the same
10123        // package name. Internally, we use a synthetic package name to allow
10124        // multiple versions of the same shared library to be installed. So,
10125        // we need to generate the synthetic package name of the latest shared
10126        // library in order to compare signatures.
10127        PackageSetting signatureCheckPs = pkgSetting;
10128        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10129            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10130            if (libraryEntry != null) {
10131                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10132            }
10133        }
10134
10135        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10136        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10137            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10138                // We just determined the app is signed correctly, so bring
10139                // over the latest parsed certs.
10140                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10141            } else {
10142                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10143                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10144                            "Package " + pkg.packageName + " upgrade keys do not match the "
10145                                    + "previously installed version");
10146                } else {
10147                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10148                    String msg = "System package " + pkg.packageName
10149                            + " signature changed; retaining data.";
10150                    reportSettingsProblem(Log.WARN, msg);
10151                }
10152            }
10153        } else {
10154            try {
10155                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10156                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10157                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10158                        pkg.mSigningDetails, compareCompat, compareRecover);
10159                // The new KeySets will be re-added later in the scanning process.
10160                if (compatMatch) {
10161                    synchronized (mPackages) {
10162                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10163                    }
10164                }
10165                // We just determined the app is signed correctly, so bring
10166                // over the latest parsed certs.
10167                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10168
10169
10170                // if this is is a sharedUser, check to see if the new package is signed by a newer
10171                // signing certificate than the existing one, and if so, copy over the new details
10172                if (signatureCheckPs.sharedUser != null
10173                        && pkg.mSigningDetails.hasAncestor(
10174                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10175                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10176                }
10177            } catch (PackageManagerException e) {
10178                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10179                    throw e;
10180                }
10181                // The signature has changed, but this package is in the system
10182                // image...  let's recover!
10183                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10184                // However...  if this package is part of a shared user, but it
10185                // doesn't match the signature of the shared user, let's fail.
10186                // What this means is that you can't change the signatures
10187                // associated with an overall shared user, which doesn't seem all
10188                // that unreasonable.
10189                if (signatureCheckPs.sharedUser != null) {
10190                    if (compareSignatures(
10191                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10192                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10193                        throw new PackageManagerException(
10194                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10195                                "Signature mismatch for shared user: "
10196                                        + pkgSetting.sharedUser);
10197                    }
10198                }
10199                // File a report about this.
10200                String msg = "System package " + pkg.packageName
10201                        + " signature changed; retaining data.";
10202                reportSettingsProblem(Log.WARN, msg);
10203            } catch (IllegalArgumentException e) {
10204
10205                // should never happen: certs matched when checking, but not when comparing
10206                // old to new for sharedUser
10207                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10208                        "Signing certificates comparison made on incomparable signing details"
10209                        + " but somehow passed verifySignatures!");
10210            }
10211        }
10212
10213        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10214            // This package wants to adopt ownership of permissions from
10215            // another package.
10216            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10217                final String origName = pkg.mAdoptPermissions.get(i);
10218                final PackageSetting orig = mSettings.getPackageLPr(origName);
10219                if (orig != null) {
10220                    if (verifyPackageUpdateLPr(orig, pkg)) {
10221                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10222                                + pkg.packageName);
10223                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10224                    }
10225                }
10226            }
10227        }
10228
10229        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10230            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10231                final String codePathString = changedAbiCodePath.get(i);
10232                try {
10233                    mInstaller.rmdex(codePathString,
10234                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10235                } catch (InstallerException ignored) {
10236                }
10237            }
10238        }
10239
10240        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10241            if (oldPkgSetting != null) {
10242                synchronized (mPackages) {
10243                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10244                }
10245            }
10246        } else {
10247            final int userId = user == null ? 0 : user.getIdentifier();
10248            // Modify state for the given package setting
10249            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10250                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10251            if (pkgSetting.getInstantApp(userId)) {
10252                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10253            }
10254        }
10255    }
10256
10257    /**
10258     * Returns the "real" name of the package.
10259     * <p>This may differ from the package's actual name if the application has already
10260     * been installed under one of this package's original names.
10261     */
10262    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10263            @Nullable String renamedPkgName) {
10264        if (isPackageRenamed(pkg, renamedPkgName)) {
10265            return pkg.mRealPackage;
10266        }
10267        return null;
10268    }
10269
10270    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10271    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10272            @Nullable String renamedPkgName) {
10273        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10274    }
10275
10276    /**
10277     * Returns the original package setting.
10278     * <p>A package can migrate its name during an update. In this scenario, a package
10279     * designates a set of names that it considers as one of its original names.
10280     * <p>An original package must be signed identically and it must have the same
10281     * shared user [if any].
10282     */
10283    @GuardedBy("mPackages")
10284    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10285            @Nullable String renamedPkgName) {
10286        if (!isPackageRenamed(pkg, renamedPkgName)) {
10287            return null;
10288        }
10289        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10290            final PackageSetting originalPs =
10291                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10292            if (originalPs != null) {
10293                // the package is already installed under its original name...
10294                // but, should we use it?
10295                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10296                    // the new package is incompatible with the original
10297                    continue;
10298                } else if (originalPs.sharedUser != null) {
10299                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10300                        // the shared user id is incompatible with the original
10301                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10302                                + " to " + pkg.packageName + ": old uid "
10303                                + originalPs.sharedUser.name
10304                                + " differs from " + pkg.mSharedUserId);
10305                        continue;
10306                    }
10307                    // TODO: Add case when shared user id is added [b/28144775]
10308                } else {
10309                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10310                            + pkg.packageName + " to old name " + originalPs.name);
10311                }
10312                return originalPs;
10313            }
10314        }
10315        return null;
10316    }
10317
10318    /**
10319     * Renames the package if it was installed under a different name.
10320     * <p>When we've already installed the package under an original name, update
10321     * the new package so we can continue to have the old name.
10322     */
10323    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10324            @NonNull String renamedPackageName) {
10325        if (pkg.mOriginalPackages == null
10326                || !pkg.mOriginalPackages.contains(renamedPackageName)
10327                || pkg.packageName.equals(renamedPackageName)) {
10328            return;
10329        }
10330        pkg.setPackageName(renamedPackageName);
10331    }
10332
10333    /**
10334     * Just scans the package without any side effects.
10335     * <p>Not entirely true at the moment. There is still one side effect -- this
10336     * method potentially modifies a live {@link PackageSetting} object representing
10337     * the package being scanned. This will be resolved in the future.
10338     *
10339     * @param request Information about the package to be scanned
10340     * @param isUnderFactoryTest Whether or not the device is under factory test
10341     * @param currentTime The current time, in millis
10342     * @return The results of the scan
10343     */
10344    @GuardedBy("mInstallLock")
10345    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10346            boolean isUnderFactoryTest, long currentTime)
10347                    throws PackageManagerException {
10348        final PackageParser.Package pkg = request.pkg;
10349        PackageSetting pkgSetting = request.pkgSetting;
10350        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10351        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10352        final @ParseFlags int parseFlags = request.parseFlags;
10353        final @ScanFlags int scanFlags = request.scanFlags;
10354        final String realPkgName = request.realPkgName;
10355        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10356        final UserHandle user = request.user;
10357        final boolean isPlatformPackage = request.isPlatformPackage;
10358
10359        List<String> changedAbiCodePath = null;
10360
10361        if (DEBUG_PACKAGE_SCANNING) {
10362            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10363                Log.d(TAG, "Scanning package " + pkg.packageName);
10364        }
10365
10366        if (Build.IS_DEBUGGABLE &&
10367                pkg.isPrivileged() &&
10368                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10369            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10370        }
10371
10372        // Initialize package source and resource directories
10373        final File scanFile = new File(pkg.codePath);
10374        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10375        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10376
10377        // We keep references to the derived CPU Abis from settings in oder to reuse
10378        // them in the case where we're not upgrading or booting for the first time.
10379        String primaryCpuAbiFromSettings = null;
10380        String secondaryCpuAbiFromSettings = null;
10381        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10382
10383        if (!needToDeriveAbi) {
10384            if (pkgSetting != null) {
10385                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10386                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10387            } else {
10388                // Re-scanning a system package after uninstalling updates; need to derive ABI
10389                needToDeriveAbi = true;
10390            }
10391        }
10392
10393        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10394            PackageManagerService.reportSettingsProblem(Log.WARN,
10395                    "Package " + pkg.packageName + " shared user changed from "
10396                            + (pkgSetting.sharedUser != null
10397                            ? pkgSetting.sharedUser.name : "<nothing>")
10398                            + " to "
10399                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10400                            + "; replacing with new");
10401            pkgSetting = null;
10402        }
10403
10404        String[] usesStaticLibraries = null;
10405        if (pkg.usesStaticLibraries != null) {
10406            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10407            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10408        }
10409        final boolean createNewPackage = (pkgSetting == null);
10410        if (createNewPackage) {
10411            final String parentPackageName = (pkg.parentPackage != null)
10412                    ? pkg.parentPackage.packageName : null;
10413            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10414            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10415            // REMOVE SharedUserSetting from method; update in a separate call
10416            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10417                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10418                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10419                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10420                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10421                    user, true /*allowInstall*/, instantApp, virtualPreload,
10422                    parentPackageName, pkg.getChildPackageNames(),
10423                    UserManagerService.getInstance(), usesStaticLibraries,
10424                    pkg.usesStaticLibrariesVersions);
10425        } else {
10426            // REMOVE SharedUserSetting from method; update in a separate call.
10427            //
10428            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10429            // secondaryCpuAbi are not known at this point so we always update them
10430            // to null here, only to reset them at a later point.
10431            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10432                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10433                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10434                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10435                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10436                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10437        }
10438        if (createNewPackage && originalPkgSetting != null) {
10439            // This is the initial transition from the original package, so,
10440            // fix up the new package's name now. We must do this after looking
10441            // up the package under its new name, so getPackageLP takes care of
10442            // fiddling things correctly.
10443            pkg.setPackageName(originalPkgSetting.name);
10444
10445            // File a report about this.
10446            String msg = "New package " + pkgSetting.realName
10447                    + " renamed to replace old package " + pkgSetting.name;
10448            reportSettingsProblem(Log.WARN, msg);
10449        }
10450
10451        if (disabledPkgSetting != null) {
10452            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10453        }
10454
10455        // SELinux sandboxes become more restrictive as targetSdkVersion increases.
10456        // To ensure that apps with sharedUserId are placed in the same selinux domain
10457        // without breaking any assumptions about access, put them into the least
10458        // restrictive targetSdkVersion=25 domain.
10459        // TODO(b/72290969): Base this on the actual targetSdkVersion(s) of the apps within the
10460        // sharedUserSetting, instead of defaulting to the least restrictive domain.
10461        final int targetSdk = (sharedUserSetting != null) ? 25
10462                : pkg.applicationInfo.targetSdkVersion;
10463        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10464        // They currently can be if the sharedUser apps are signed with the platform key.
10465        final boolean isPrivileged = (sharedUserSetting != null) ?
10466            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10467
10468        SELinuxMMAC.assignSeInfoValue(pkg, isPrivileged, targetSdk);
10469
10470        pkg.mExtras = pkgSetting;
10471        pkg.applicationInfo.processName = fixProcessName(
10472                pkg.applicationInfo.packageName,
10473                pkg.applicationInfo.processName);
10474
10475        if (!isPlatformPackage) {
10476            // Get all of our default paths setup
10477            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10478        }
10479
10480        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10481
10482        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10483            if (needToDeriveAbi) {
10484                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10485                final boolean extractNativeLibs = !pkg.isLibrary();
10486                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10487                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10488
10489                // Some system apps still use directory structure for native libraries
10490                // in which case we might end up not detecting abi solely based on apk
10491                // structure. Try to detect abi based on directory structure.
10492                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10493                        pkg.applicationInfo.primaryCpuAbi == null) {
10494                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10495                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10496                }
10497            } else {
10498                // This is not a first boot or an upgrade, don't bother deriving the
10499                // ABI during the scan. Instead, trust the value that was stored in the
10500                // package setting.
10501                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10502                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10503
10504                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10505
10506                if (DEBUG_ABI_SELECTION) {
10507                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10508                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10509                            pkg.applicationInfo.secondaryCpuAbi);
10510                }
10511            }
10512        } else {
10513            if ((scanFlags & SCAN_MOVE) != 0) {
10514                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10515                // but we already have this packages package info in the PackageSetting. We just
10516                // use that and derive the native library path based on the new codepath.
10517                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10518                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10519            }
10520
10521            // Set native library paths again. For moves, the path will be updated based on the
10522            // ABIs we've determined above. For non-moves, the path will be updated based on the
10523            // ABIs we determined during compilation, but the path will depend on the final
10524            // package path (after the rename away from the stage path).
10525            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10526        }
10527
10528        // This is a special case for the "system" package, where the ABI is
10529        // dictated by the zygote configuration (and init.rc). We should keep track
10530        // of this ABI so that we can deal with "normal" applications that run under
10531        // the same UID correctly.
10532        if (isPlatformPackage) {
10533            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10534                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10535        }
10536
10537        // If there's a mismatch between the abi-override in the package setting
10538        // and the abiOverride specified for the install. Warn about this because we
10539        // would've already compiled the app without taking the package setting into
10540        // account.
10541        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10542            if (cpuAbiOverride == null && pkg.packageName != null) {
10543                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10544                        " for package " + pkg.packageName);
10545            }
10546        }
10547
10548        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10549        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10550        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10551
10552        // Copy the derived override back to the parsed package, so that we can
10553        // update the package settings accordingly.
10554        pkg.cpuAbiOverride = cpuAbiOverride;
10555
10556        if (DEBUG_ABI_SELECTION) {
10557            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10558                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10559                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10560        }
10561
10562        // Push the derived path down into PackageSettings so we know what to
10563        // clean up at uninstall time.
10564        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10565
10566        if (DEBUG_ABI_SELECTION) {
10567            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10568                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10569                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10570        }
10571
10572        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10573            // We don't do this here during boot because we can do it all
10574            // at once after scanning all existing packages.
10575            //
10576            // We also do this *before* we perform dexopt on this package, so that
10577            // we can avoid redundant dexopts, and also to make sure we've got the
10578            // code and package path correct.
10579            changedAbiCodePath =
10580                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10581        }
10582
10583        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10584                android.Manifest.permission.FACTORY_TEST)) {
10585            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10586        }
10587
10588        if (isSystemApp(pkg)) {
10589            pkgSetting.isOrphaned = true;
10590        }
10591
10592        // Take care of first install / last update times.
10593        final long scanFileTime = getLastModifiedTime(pkg);
10594        if (currentTime != 0) {
10595            if (pkgSetting.firstInstallTime == 0) {
10596                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10597            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10598                pkgSetting.lastUpdateTime = currentTime;
10599            }
10600        } else if (pkgSetting.firstInstallTime == 0) {
10601            // We need *something*.  Take time time stamp of the file.
10602            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10603        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10604            if (scanFileTime != pkgSetting.timeStamp) {
10605                // A package on the system image has changed; consider this
10606                // to be an update.
10607                pkgSetting.lastUpdateTime = scanFileTime;
10608            }
10609        }
10610        pkgSetting.setTimeStamp(scanFileTime);
10611
10612        pkgSetting.pkg = pkg;
10613        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10614        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10615            pkgSetting.versionCode = pkg.getLongVersionCode();
10616        }
10617        // Update volume if needed
10618        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10619        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10620            Slog.i(PackageManagerService.TAG,
10621                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10622                    + " package " + pkg.packageName
10623                    + " volume from " + pkgSetting.volumeUuid
10624                    + " to " + volumeUuid);
10625            pkgSetting.volumeUuid = volumeUuid;
10626        }
10627
10628        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10629    }
10630
10631    /**
10632     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10633     */
10634    private static boolean apkHasCode(String fileName) {
10635        StrictJarFile jarFile = null;
10636        try {
10637            jarFile = new StrictJarFile(fileName,
10638                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10639            return jarFile.findEntry("classes.dex") != null;
10640        } catch (IOException ignore) {
10641        } finally {
10642            try {
10643                if (jarFile != null) {
10644                    jarFile.close();
10645                }
10646            } catch (IOException ignore) {}
10647        }
10648        return false;
10649    }
10650
10651    /**
10652     * Enforces code policy for the package. This ensures that if an APK has
10653     * declared hasCode="true" in its manifest that the APK actually contains
10654     * code.
10655     *
10656     * @throws PackageManagerException If bytecode could not be found when it should exist
10657     */
10658    private static void assertCodePolicy(PackageParser.Package pkg)
10659            throws PackageManagerException {
10660        final boolean shouldHaveCode =
10661                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10662        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10663            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10664                    "Package " + pkg.baseCodePath + " code is missing");
10665        }
10666
10667        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10668            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10669                final boolean splitShouldHaveCode =
10670                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10671                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10672                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10673                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10674                }
10675            }
10676        }
10677    }
10678
10679    /**
10680     * Applies policy to the parsed package based upon the given policy flags.
10681     * Ensures the package is in a good state.
10682     * <p>
10683     * Implementation detail: This method must NOT have any side effect. It would
10684     * ideally be static, but, it requires locks to read system state.
10685     */
10686    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10687            final @ScanFlags int scanFlags) {
10688        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10689            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10690            if (pkg.applicationInfo.isDirectBootAware()) {
10691                // we're direct boot aware; set for all components
10692                for (PackageParser.Service s : pkg.services) {
10693                    s.info.encryptionAware = s.info.directBootAware = true;
10694                }
10695                for (PackageParser.Provider p : pkg.providers) {
10696                    p.info.encryptionAware = p.info.directBootAware = true;
10697                }
10698                for (PackageParser.Activity a : pkg.activities) {
10699                    a.info.encryptionAware = a.info.directBootAware = true;
10700                }
10701                for (PackageParser.Activity r : pkg.receivers) {
10702                    r.info.encryptionAware = r.info.directBootAware = true;
10703                }
10704            }
10705            if (compressedFileExists(pkg.codePath)) {
10706                pkg.isStub = true;
10707            }
10708        } else {
10709            // non system apps can't be flagged as core
10710            pkg.coreApp = false;
10711            // clear flags not applicable to regular apps
10712            pkg.applicationInfo.flags &=
10713                    ~ApplicationInfo.FLAG_PERSISTENT;
10714            pkg.applicationInfo.privateFlags &=
10715                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10716            pkg.applicationInfo.privateFlags &=
10717                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10718            // clear protected broadcasts
10719            pkg.protectedBroadcasts = null;
10720            // cap permission priorities
10721            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10722                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10723                    pkg.permissionGroups.get(i).info.priority = 0;
10724                }
10725            }
10726        }
10727        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10728            // ignore export request for single user receivers
10729            if (pkg.receivers != null) {
10730                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10731                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10732                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10733                        receiver.info.exported = false;
10734                    }
10735                }
10736            }
10737            // ignore export request for single user services
10738            if (pkg.services != null) {
10739                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10740                    final PackageParser.Service service = pkg.services.get(i);
10741                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10742                        service.info.exported = false;
10743                    }
10744                }
10745            }
10746            // ignore export request for single user providers
10747            if (pkg.providers != null) {
10748                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10749                    final PackageParser.Provider provider = pkg.providers.get(i);
10750                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10751                        provider.info.exported = false;
10752                    }
10753                }
10754            }
10755        }
10756
10757        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10758            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10759        }
10760
10761        if ((scanFlags & SCAN_AS_OEM) != 0) {
10762            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10763        }
10764
10765        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10766            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10767        }
10768
10769        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10770            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10771        }
10772
10773        if (!isSystemApp(pkg)) {
10774            // Only system apps can use these features.
10775            pkg.mOriginalPackages = null;
10776            pkg.mRealPackage = null;
10777            pkg.mAdoptPermissions = null;
10778        }
10779    }
10780
10781    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10782            throws PackageManagerException {
10783        if (object == null) {
10784            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10785        }
10786        return object;
10787    }
10788
10789    /**
10790     * Asserts the parsed package is valid according to the given policy. If the
10791     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10792     * <p>
10793     * Implementation detail: This method must NOT have any side effects. It would
10794     * ideally be static, but, it requires locks to read system state.
10795     *
10796     * @throws PackageManagerException If the package fails any of the validation checks
10797     */
10798    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10799            final @ScanFlags int scanFlags)
10800                    throws PackageManagerException {
10801        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10802            assertCodePolicy(pkg);
10803        }
10804
10805        if (pkg.applicationInfo.getCodePath() == null ||
10806                pkg.applicationInfo.getResourcePath() == null) {
10807            // Bail out. The resource and code paths haven't been set.
10808            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10809                    "Code and resource paths haven't been set correctly");
10810        }
10811
10812        // Make sure we're not adding any bogus keyset info
10813        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10814        ksms.assertScannedPackageValid(pkg);
10815
10816        synchronized (mPackages) {
10817            // The special "android" package can only be defined once
10818            if (pkg.packageName.equals("android")) {
10819                if (mAndroidApplication != null) {
10820                    Slog.w(TAG, "*************************************************");
10821                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10822                    Slog.w(TAG, " codePath=" + pkg.codePath);
10823                    Slog.w(TAG, "*************************************************");
10824                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10825                            "Core android package being redefined.  Skipping.");
10826                }
10827            }
10828
10829            // A package name must be unique; don't allow duplicates
10830            if (mPackages.containsKey(pkg.packageName)) {
10831                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10832                        "Application package " + pkg.packageName
10833                        + " already installed.  Skipping duplicate.");
10834            }
10835
10836            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10837                // Static libs have a synthetic package name containing the version
10838                // but we still want the base name to be unique.
10839                if (mPackages.containsKey(pkg.manifestPackageName)) {
10840                    throw new PackageManagerException(
10841                            "Duplicate static shared lib provider package");
10842                }
10843
10844                // Static shared libraries should have at least O target SDK
10845                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10846                    throw new PackageManagerException(
10847                            "Packages declaring static-shared libs must target O SDK or higher");
10848                }
10849
10850                // Package declaring static a shared lib cannot be instant apps
10851                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10852                    throw new PackageManagerException(
10853                            "Packages declaring static-shared libs cannot be instant apps");
10854                }
10855
10856                // Package declaring static a shared lib cannot be renamed since the package
10857                // name is synthetic and apps can't code around package manager internals.
10858                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10859                    throw new PackageManagerException(
10860                            "Packages declaring static-shared libs cannot be renamed");
10861                }
10862
10863                // Package declaring static a shared lib cannot declare child packages
10864                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10865                    throw new PackageManagerException(
10866                            "Packages declaring static-shared libs cannot have child packages");
10867                }
10868
10869                // Package declaring static a shared lib cannot declare dynamic libs
10870                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10871                    throw new PackageManagerException(
10872                            "Packages declaring static-shared libs cannot declare dynamic libs");
10873                }
10874
10875                // Package declaring static a shared lib cannot declare shared users
10876                if (pkg.mSharedUserId != null) {
10877                    throw new PackageManagerException(
10878                            "Packages declaring static-shared libs cannot declare shared users");
10879                }
10880
10881                // Static shared libs cannot declare activities
10882                if (!pkg.activities.isEmpty()) {
10883                    throw new PackageManagerException(
10884                            "Static shared libs cannot declare activities");
10885                }
10886
10887                // Static shared libs cannot declare services
10888                if (!pkg.services.isEmpty()) {
10889                    throw new PackageManagerException(
10890                            "Static shared libs cannot declare services");
10891                }
10892
10893                // Static shared libs cannot declare providers
10894                if (!pkg.providers.isEmpty()) {
10895                    throw new PackageManagerException(
10896                            "Static shared libs cannot declare content providers");
10897                }
10898
10899                // Static shared libs cannot declare receivers
10900                if (!pkg.receivers.isEmpty()) {
10901                    throw new PackageManagerException(
10902                            "Static shared libs cannot declare broadcast receivers");
10903                }
10904
10905                // Static shared libs cannot declare permission groups
10906                if (!pkg.permissionGroups.isEmpty()) {
10907                    throw new PackageManagerException(
10908                            "Static shared libs cannot declare permission groups");
10909                }
10910
10911                // Static shared libs cannot declare permissions
10912                if (!pkg.permissions.isEmpty()) {
10913                    throw new PackageManagerException(
10914                            "Static shared libs cannot declare permissions");
10915                }
10916
10917                // Static shared libs cannot declare protected broadcasts
10918                if (pkg.protectedBroadcasts != null) {
10919                    throw new PackageManagerException(
10920                            "Static shared libs cannot declare protected broadcasts");
10921                }
10922
10923                // Static shared libs cannot be overlay targets
10924                if (pkg.mOverlayTarget != null) {
10925                    throw new PackageManagerException(
10926                            "Static shared libs cannot be overlay targets");
10927                }
10928
10929                // The version codes must be ordered as lib versions
10930                long minVersionCode = Long.MIN_VALUE;
10931                long maxVersionCode = Long.MAX_VALUE;
10932
10933                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10934                        pkg.staticSharedLibName);
10935                if (versionedLib != null) {
10936                    final int versionCount = versionedLib.size();
10937                    for (int i = 0; i < versionCount; i++) {
10938                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10939                        final long libVersionCode = libInfo.getDeclaringPackage()
10940                                .getLongVersionCode();
10941                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10942                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10943                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10944                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10945                        } else {
10946                            minVersionCode = maxVersionCode = libVersionCode;
10947                            break;
10948                        }
10949                    }
10950                }
10951                if (pkg.getLongVersionCode() < minVersionCode
10952                        || pkg.getLongVersionCode() > maxVersionCode) {
10953                    throw new PackageManagerException("Static shared"
10954                            + " lib version codes must be ordered as lib versions");
10955                }
10956            }
10957
10958            // Only privileged apps and updated privileged apps can add child packages.
10959            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10960                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10961                    throw new PackageManagerException("Only privileged apps can add child "
10962                            + "packages. Ignoring package " + pkg.packageName);
10963                }
10964                final int childCount = pkg.childPackages.size();
10965                for (int i = 0; i < childCount; i++) {
10966                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10967                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10968                            childPkg.packageName)) {
10969                        throw new PackageManagerException("Can't override child of "
10970                                + "another disabled app. Ignoring package " + pkg.packageName);
10971                    }
10972                }
10973            }
10974
10975            // If we're only installing presumed-existing packages, require that the
10976            // scanned APK is both already known and at the path previously established
10977            // for it.  Previously unknown packages we pick up normally, but if we have an
10978            // a priori expectation about this package's install presence, enforce it.
10979            // With a singular exception for new system packages. When an OTA contains
10980            // a new system package, we allow the codepath to change from a system location
10981            // to the user-installed location. If we don't allow this change, any newer,
10982            // user-installed version of the application will be ignored.
10983            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10984                if (mExpectingBetter.containsKey(pkg.packageName)) {
10985                    logCriticalInfo(Log.WARN,
10986                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10987                } else {
10988                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10989                    if (known != null) {
10990                        if (DEBUG_PACKAGE_SCANNING) {
10991                            Log.d(TAG, "Examining " + pkg.codePath
10992                                    + " and requiring known paths " + known.codePathString
10993                                    + " & " + known.resourcePathString);
10994                        }
10995                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10996                                || !pkg.applicationInfo.getResourcePath().equals(
10997                                        known.resourcePathString)) {
10998                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10999                                    "Application package " + pkg.packageName
11000                                    + " found at " + pkg.applicationInfo.getCodePath()
11001                                    + " but expected at " + known.codePathString
11002                                    + "; ignoring.");
11003                        }
11004                    } else {
11005                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11006                                "Application package " + pkg.packageName
11007                                + " not found; ignoring.");
11008                    }
11009                }
11010            }
11011
11012            // Verify that this new package doesn't have any content providers
11013            // that conflict with existing packages.  Only do this if the
11014            // package isn't already installed, since we don't want to break
11015            // things that are installed.
11016            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11017                final int N = pkg.providers.size();
11018                int i;
11019                for (i=0; i<N; i++) {
11020                    PackageParser.Provider p = pkg.providers.get(i);
11021                    if (p.info.authority != null) {
11022                        String names[] = p.info.authority.split(";");
11023                        for (int j = 0; j < names.length; j++) {
11024                            if (mProvidersByAuthority.containsKey(names[j])) {
11025                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11026                                final String otherPackageName =
11027                                        ((other != null && other.getComponentName() != null) ?
11028                                                other.getComponentName().getPackageName() : "?");
11029                                throw new PackageManagerException(
11030                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11031                                        "Can't install because provider name " + names[j]
11032                                                + " (in package " + pkg.applicationInfo.packageName
11033                                                + ") is already used by " + otherPackageName);
11034                            }
11035                        }
11036                    }
11037                }
11038            }
11039
11040            // Verify that packages sharing a user with a privileged app are marked as privileged.
11041            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11042                SharedUserSetting sharedUserSetting = null;
11043                try {
11044                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11045                } catch (PackageManagerException ignore) {}
11046                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11047                    // Exempt SharedUsers signed with the platform key.
11048                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11049                    if ((platformPkgSetting.signatures.mSigningDetails
11050                            != PackageParser.SigningDetails.UNKNOWN)
11051                            && (compareSignatures(
11052                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11053                                    pkg.mSigningDetails.signatures)
11054                                            != PackageManager.SIGNATURE_MATCH)) {
11055                        throw new PackageManagerException("Apps that share a user with a " +
11056                                "privileged app must themselves be marked as privileged. " +
11057                                pkg.packageName + " shares privileged user " +
11058                                pkg.mSharedUserId + ".");
11059                    }
11060                }
11061            }
11062
11063            // Apply policies specific for runtime resource overlays (RROs).
11064            if (pkg.mOverlayTarget != null) {
11065                // System overlays have some restrictions on their use of the 'static' state.
11066                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11067                    // We are scanning a system overlay. This can be the first scan of the
11068                    // system/vendor/oem partition, or an update to the system overlay.
11069                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11070                        // This must be an update to a system overlay.
11071                        final PackageSetting previousPkg = assertNotNull(
11072                                mSettings.getPackageLPr(pkg.packageName),
11073                                "previous package state not present");
11074
11075                        // Static overlays cannot be updated.
11076                        if (previousPkg.pkg.mOverlayIsStatic) {
11077                            throw new PackageManagerException("Overlay " + pkg.packageName +
11078                                    " is static and cannot be upgraded.");
11079                        // Non-static overlays cannot be converted to static overlays.
11080                        } else if (pkg.mOverlayIsStatic) {
11081                            throw new PackageManagerException("Overlay " + pkg.packageName +
11082                                    " cannot be upgraded into a static overlay.");
11083                        }
11084                    }
11085                } else {
11086                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11087                    if (pkg.mOverlayIsStatic) {
11088                        throw new PackageManagerException("Overlay " + pkg.packageName +
11089                                " is static but not pre-installed.");
11090                    }
11091
11092                    // The only case where we allow installation of a non-system overlay is when
11093                    // its signature is signed with the platform certificate.
11094                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11095                    if ((platformPkgSetting.signatures.mSigningDetails
11096                            != PackageParser.SigningDetails.UNKNOWN)
11097                            && (compareSignatures(
11098                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11099                                    pkg.mSigningDetails.signatures)
11100                                            != PackageManager.SIGNATURE_MATCH)) {
11101                        throw new PackageManagerException("Overlay " + pkg.packageName +
11102                                " must be signed with the platform certificate.");
11103                    }
11104                }
11105            }
11106        }
11107    }
11108
11109    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11110            int type, String declaringPackageName, long declaringVersionCode) {
11111        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11112        if (versionedLib == null) {
11113            versionedLib = new LongSparseArray<>();
11114            mSharedLibraries.put(name, versionedLib);
11115            if (type == SharedLibraryInfo.TYPE_STATIC) {
11116                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11117            }
11118        } else if (versionedLib.indexOfKey(version) >= 0) {
11119            return false;
11120        }
11121        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11122                version, type, declaringPackageName, declaringVersionCode);
11123        versionedLib.put(version, libEntry);
11124        return true;
11125    }
11126
11127    private boolean removeSharedLibraryLPw(String name, long version) {
11128        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11129        if (versionedLib == null) {
11130            return false;
11131        }
11132        final int libIdx = versionedLib.indexOfKey(version);
11133        if (libIdx < 0) {
11134            return false;
11135        }
11136        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11137        versionedLib.remove(version);
11138        if (versionedLib.size() <= 0) {
11139            mSharedLibraries.remove(name);
11140            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11141                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11142                        .getPackageName());
11143            }
11144        }
11145        return true;
11146    }
11147
11148    /**
11149     * Adds a scanned package to the system. When this method is finished, the package will
11150     * be available for query, resolution, etc...
11151     */
11152    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11153            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11154        final String pkgName = pkg.packageName;
11155        if (mCustomResolverComponentName != null &&
11156                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11157            setUpCustomResolverActivity(pkg);
11158        }
11159
11160        if (pkg.packageName.equals("android")) {
11161            synchronized (mPackages) {
11162                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11163                    // Set up information for our fall-back user intent resolution activity.
11164                    mPlatformPackage = pkg;
11165                    pkg.mVersionCode = mSdkVersion;
11166                    pkg.mVersionCodeMajor = 0;
11167                    mAndroidApplication = pkg.applicationInfo;
11168                    if (!mResolverReplaced) {
11169                        mResolveActivity.applicationInfo = mAndroidApplication;
11170                        mResolveActivity.name = ResolverActivity.class.getName();
11171                        mResolveActivity.packageName = mAndroidApplication.packageName;
11172                        mResolveActivity.processName = "system:ui";
11173                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11174                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11175                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11176                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11177                        mResolveActivity.exported = true;
11178                        mResolveActivity.enabled = true;
11179                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11180                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11181                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11182                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11183                                | ActivityInfo.CONFIG_ORIENTATION
11184                                | ActivityInfo.CONFIG_KEYBOARD
11185                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11186                        mResolveInfo.activityInfo = mResolveActivity;
11187                        mResolveInfo.priority = 0;
11188                        mResolveInfo.preferredOrder = 0;
11189                        mResolveInfo.match = 0;
11190                        mResolveComponentName = new ComponentName(
11191                                mAndroidApplication.packageName, mResolveActivity.name);
11192                    }
11193                }
11194            }
11195        }
11196
11197        ArrayList<PackageParser.Package> clientLibPkgs = null;
11198        // writer
11199        synchronized (mPackages) {
11200            boolean hasStaticSharedLibs = false;
11201
11202            // Any app can add new static shared libraries
11203            if (pkg.staticSharedLibName != null) {
11204                // Static shared libs don't allow renaming as they have synthetic package
11205                // names to allow install of multiple versions, so use name from manifest.
11206                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11207                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11208                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11209                    hasStaticSharedLibs = true;
11210                } else {
11211                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11212                                + pkg.staticSharedLibName + " already exists; skipping");
11213                }
11214                // Static shared libs cannot be updated once installed since they
11215                // use synthetic package name which includes the version code, so
11216                // not need to update other packages's shared lib dependencies.
11217            }
11218
11219            if (!hasStaticSharedLibs
11220                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11221                // Only system apps can add new dynamic shared libraries.
11222                if (pkg.libraryNames != null) {
11223                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11224                        String name = pkg.libraryNames.get(i);
11225                        boolean allowed = false;
11226                        if (pkg.isUpdatedSystemApp()) {
11227                            // New library entries can only be added through the
11228                            // system image.  This is important to get rid of a lot
11229                            // of nasty edge cases: for example if we allowed a non-
11230                            // system update of the app to add a library, then uninstalling
11231                            // the update would make the library go away, and assumptions
11232                            // we made such as through app install filtering would now
11233                            // have allowed apps on the device which aren't compatible
11234                            // with it.  Better to just have the restriction here, be
11235                            // conservative, and create many fewer cases that can negatively
11236                            // impact the user experience.
11237                            final PackageSetting sysPs = mSettings
11238                                    .getDisabledSystemPkgLPr(pkg.packageName);
11239                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11240                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11241                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11242                                        allowed = true;
11243                                        break;
11244                                    }
11245                                }
11246                            }
11247                        } else {
11248                            allowed = true;
11249                        }
11250                        if (allowed) {
11251                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11252                                    SharedLibraryInfo.VERSION_UNDEFINED,
11253                                    SharedLibraryInfo.TYPE_DYNAMIC,
11254                                    pkg.packageName, pkg.getLongVersionCode())) {
11255                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11256                                        + name + " already exists; skipping");
11257                            }
11258                        } else {
11259                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11260                                    + name + " that is not declared on system image; skipping");
11261                        }
11262                    }
11263
11264                    if ((scanFlags & SCAN_BOOTING) == 0) {
11265                        // If we are not booting, we need to update any applications
11266                        // that are clients of our shared library.  If we are booting,
11267                        // this will all be done once the scan is complete.
11268                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11269                    }
11270                }
11271            }
11272        }
11273
11274        if ((scanFlags & SCAN_BOOTING) != 0) {
11275            // No apps can run during boot scan, so they don't need to be frozen
11276        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11277            // Caller asked to not kill app, so it's probably not frozen
11278        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11279            // Caller asked us to ignore frozen check for some reason; they
11280            // probably didn't know the package name
11281        } else {
11282            // We're doing major surgery on this package, so it better be frozen
11283            // right now to keep it from launching
11284            checkPackageFrozen(pkgName);
11285        }
11286
11287        // Also need to kill any apps that are dependent on the library.
11288        if (clientLibPkgs != null) {
11289            for (int i=0; i<clientLibPkgs.size(); i++) {
11290                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11291                killApplication(clientPkg.applicationInfo.packageName,
11292                        clientPkg.applicationInfo.uid, "update lib");
11293            }
11294        }
11295
11296        // writer
11297        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11298
11299        synchronized (mPackages) {
11300            // We don't expect installation to fail beyond this point
11301
11302            // Add the new setting to mSettings
11303            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11304            // Add the new setting to mPackages
11305            mPackages.put(pkg.applicationInfo.packageName, pkg);
11306            // Make sure we don't accidentally delete its data.
11307            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11308            while (iter.hasNext()) {
11309                PackageCleanItem item = iter.next();
11310                if (pkgName.equals(item.packageName)) {
11311                    iter.remove();
11312                }
11313            }
11314
11315            // Add the package's KeySets to the global KeySetManagerService
11316            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11317            ksms.addScannedPackageLPw(pkg);
11318
11319            int N = pkg.providers.size();
11320            StringBuilder r = null;
11321            int i;
11322            for (i=0; i<N; i++) {
11323                PackageParser.Provider p = pkg.providers.get(i);
11324                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11325                        p.info.processName);
11326                mProviders.addProvider(p);
11327                p.syncable = p.info.isSyncable;
11328                if (p.info.authority != null) {
11329                    String names[] = p.info.authority.split(";");
11330                    p.info.authority = null;
11331                    for (int j = 0; j < names.length; j++) {
11332                        if (j == 1 && p.syncable) {
11333                            // We only want the first authority for a provider to possibly be
11334                            // syncable, so if we already added this provider using a different
11335                            // authority clear the syncable flag. We copy the provider before
11336                            // changing it because the mProviders object contains a reference
11337                            // to a provider that we don't want to change.
11338                            // Only do this for the second authority since the resulting provider
11339                            // object can be the same for all future authorities for this provider.
11340                            p = new PackageParser.Provider(p);
11341                            p.syncable = false;
11342                        }
11343                        if (!mProvidersByAuthority.containsKey(names[j])) {
11344                            mProvidersByAuthority.put(names[j], p);
11345                            if (p.info.authority == null) {
11346                                p.info.authority = names[j];
11347                            } else {
11348                                p.info.authority = p.info.authority + ";" + names[j];
11349                            }
11350                            if (DEBUG_PACKAGE_SCANNING) {
11351                                if (chatty)
11352                                    Log.d(TAG, "Registered content provider: " + names[j]
11353                                            + ", className = " + p.info.name + ", isSyncable = "
11354                                            + p.info.isSyncable);
11355                            }
11356                        } else {
11357                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11358                            Slog.w(TAG, "Skipping provider name " + names[j] +
11359                                    " (in package " + pkg.applicationInfo.packageName +
11360                                    "): name already used by "
11361                                    + ((other != null && other.getComponentName() != null)
11362                                            ? other.getComponentName().getPackageName() : "?"));
11363                        }
11364                    }
11365                }
11366                if (chatty) {
11367                    if (r == null) {
11368                        r = new StringBuilder(256);
11369                    } else {
11370                        r.append(' ');
11371                    }
11372                    r.append(p.info.name);
11373                }
11374            }
11375            if (r != null) {
11376                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11377            }
11378
11379            N = pkg.services.size();
11380            r = null;
11381            for (i=0; i<N; i++) {
11382                PackageParser.Service s = pkg.services.get(i);
11383                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11384                        s.info.processName);
11385                mServices.addService(s);
11386                if (chatty) {
11387                    if (r == null) {
11388                        r = new StringBuilder(256);
11389                    } else {
11390                        r.append(' ');
11391                    }
11392                    r.append(s.info.name);
11393                }
11394            }
11395            if (r != null) {
11396                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11397            }
11398
11399            N = pkg.receivers.size();
11400            r = null;
11401            for (i=0; i<N; i++) {
11402                PackageParser.Activity a = pkg.receivers.get(i);
11403                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11404                        a.info.processName);
11405                mReceivers.addActivity(a, "receiver");
11406                if (chatty) {
11407                    if (r == null) {
11408                        r = new StringBuilder(256);
11409                    } else {
11410                        r.append(' ');
11411                    }
11412                    r.append(a.info.name);
11413                }
11414            }
11415            if (r != null) {
11416                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11417            }
11418
11419            N = pkg.activities.size();
11420            r = null;
11421            for (i=0; i<N; i++) {
11422                PackageParser.Activity a = pkg.activities.get(i);
11423                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11424                        a.info.processName);
11425                mActivities.addActivity(a, "activity");
11426                if (chatty) {
11427                    if (r == null) {
11428                        r = new StringBuilder(256);
11429                    } else {
11430                        r.append(' ');
11431                    }
11432                    r.append(a.info.name);
11433                }
11434            }
11435            if (r != null) {
11436                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11437            }
11438
11439            // Don't allow ephemeral applications to define new permissions groups.
11440            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11441                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11442                        + " ignored: instant apps cannot define new permission groups.");
11443            } else {
11444                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11445            }
11446
11447            // Don't allow ephemeral applications to define new permissions.
11448            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11449                Slog.w(TAG, "Permissions from package " + pkg.packageName
11450                        + " ignored: instant apps cannot define new permissions.");
11451            } else {
11452                mPermissionManager.addAllPermissions(pkg, chatty);
11453            }
11454
11455            N = pkg.instrumentation.size();
11456            r = null;
11457            for (i=0; i<N; i++) {
11458                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11459                a.info.packageName = pkg.applicationInfo.packageName;
11460                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11461                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11462                a.info.splitNames = pkg.splitNames;
11463                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11464                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11465                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11466                a.info.dataDir = pkg.applicationInfo.dataDir;
11467                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11468                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11469                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11470                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11471                mInstrumentation.put(a.getComponentName(), a);
11472                if (chatty) {
11473                    if (r == null) {
11474                        r = new StringBuilder(256);
11475                    } else {
11476                        r.append(' ');
11477                    }
11478                    r.append(a.info.name);
11479                }
11480            }
11481            if (r != null) {
11482                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11483            }
11484
11485            if (pkg.protectedBroadcasts != null) {
11486                N = pkg.protectedBroadcasts.size();
11487                synchronized (mProtectedBroadcasts) {
11488                    for (i = 0; i < N; i++) {
11489                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11490                    }
11491                }
11492            }
11493        }
11494
11495        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11496    }
11497
11498    /**
11499     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11500     * is derived purely on the basis of the contents of {@code scanFile} and
11501     * {@code cpuAbiOverride}.
11502     *
11503     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11504     */
11505    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11506            boolean extractLibs)
11507                    throws PackageManagerException {
11508        // Give ourselves some initial paths; we'll come back for another
11509        // pass once we've determined ABI below.
11510        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11511
11512        // We would never need to extract libs for forward-locked and external packages,
11513        // since the container service will do it for us. We shouldn't attempt to
11514        // extract libs from system app when it was not updated.
11515        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11516                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11517            extractLibs = false;
11518        }
11519
11520        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11521        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11522
11523        NativeLibraryHelper.Handle handle = null;
11524        try {
11525            handle = NativeLibraryHelper.Handle.create(pkg);
11526            // TODO(multiArch): This can be null for apps that didn't go through the
11527            // usual installation process. We can calculate it again, like we
11528            // do during install time.
11529            //
11530            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11531            // unnecessary.
11532            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11533
11534            // Null out the abis so that they can be recalculated.
11535            pkg.applicationInfo.primaryCpuAbi = null;
11536            pkg.applicationInfo.secondaryCpuAbi = null;
11537            if (isMultiArch(pkg.applicationInfo)) {
11538                // Warn if we've set an abiOverride for multi-lib packages..
11539                // By definition, we need to copy both 32 and 64 bit libraries for
11540                // such packages.
11541                if (pkg.cpuAbiOverride != null
11542                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11543                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11544                }
11545
11546                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11547                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11548                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11549                    if (extractLibs) {
11550                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11551                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11552                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11553                                useIsaSpecificSubdirs);
11554                    } else {
11555                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11556                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11557                    }
11558                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11559                }
11560
11561                // Shared library native code should be in the APK zip aligned
11562                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11563                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11564                            "Shared library native lib extraction not supported");
11565                }
11566
11567                maybeThrowExceptionForMultiArchCopy(
11568                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11569
11570                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11571                    if (extractLibs) {
11572                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11573                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11574                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11575                                useIsaSpecificSubdirs);
11576                    } else {
11577                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11578                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11579                    }
11580                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11581                }
11582
11583                maybeThrowExceptionForMultiArchCopy(
11584                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11585
11586                if (abi64 >= 0) {
11587                    // Shared library native libs should be in the APK zip aligned
11588                    if (extractLibs && pkg.isLibrary()) {
11589                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11590                                "Shared library native lib extraction not supported");
11591                    }
11592                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11593                }
11594
11595                if (abi32 >= 0) {
11596                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11597                    if (abi64 >= 0) {
11598                        if (pkg.use32bitAbi) {
11599                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11600                            pkg.applicationInfo.primaryCpuAbi = abi;
11601                        } else {
11602                            pkg.applicationInfo.secondaryCpuAbi = abi;
11603                        }
11604                    } else {
11605                        pkg.applicationInfo.primaryCpuAbi = abi;
11606                    }
11607                }
11608            } else {
11609                String[] abiList = (cpuAbiOverride != null) ?
11610                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11611
11612                // Enable gross and lame hacks for apps that are built with old
11613                // SDK tools. We must scan their APKs for renderscript bitcode and
11614                // not launch them if it's present. Don't bother checking on devices
11615                // that don't have 64 bit support.
11616                boolean needsRenderScriptOverride = false;
11617                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11618                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11619                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11620                    needsRenderScriptOverride = true;
11621                }
11622
11623                final int copyRet;
11624                if (extractLibs) {
11625                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11626                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11627                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11628                } else {
11629                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11630                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11631                }
11632                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11633
11634                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11635                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11636                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11637                }
11638
11639                if (copyRet >= 0) {
11640                    // Shared libraries that have native libs must be multi-architecture
11641                    if (pkg.isLibrary()) {
11642                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11643                                "Shared library with native libs must be multiarch");
11644                    }
11645                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11646                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11647                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11648                } else if (needsRenderScriptOverride) {
11649                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11650                }
11651            }
11652        } catch (IOException ioe) {
11653            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11654        } finally {
11655            IoUtils.closeQuietly(handle);
11656        }
11657
11658        // Now that we've calculated the ABIs and determined if it's an internal app,
11659        // we will go ahead and populate the nativeLibraryPath.
11660        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11661    }
11662
11663    /**
11664     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11665     * i.e, so that all packages can be run inside a single process if required.
11666     *
11667     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11668     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11669     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11670     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11671     * updating a package that belongs to a shared user.
11672     *
11673     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11674     * adds unnecessary complexity.
11675     */
11676    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11677            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11678        List<String> changedAbiCodePath = null;
11679        String requiredInstructionSet = null;
11680        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11681            requiredInstructionSet = VMRuntime.getInstructionSet(
11682                     scannedPackage.applicationInfo.primaryCpuAbi);
11683        }
11684
11685        PackageSetting requirer = null;
11686        for (PackageSetting ps : packagesForUser) {
11687            // If packagesForUser contains scannedPackage, we skip it. This will happen
11688            // when scannedPackage is an update of an existing package. Without this check,
11689            // we will never be able to change the ABI of any package belonging to a shared
11690            // user, even if it's compatible with other packages.
11691            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11692                if (ps.primaryCpuAbiString == null) {
11693                    continue;
11694                }
11695
11696                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11697                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11698                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11699                    // this but there's not much we can do.
11700                    String errorMessage = "Instruction set mismatch, "
11701                            + ((requirer == null) ? "[caller]" : requirer)
11702                            + " requires " + requiredInstructionSet + " whereas " + ps
11703                            + " requires " + instructionSet;
11704                    Slog.w(TAG, errorMessage);
11705                }
11706
11707                if (requiredInstructionSet == null) {
11708                    requiredInstructionSet = instructionSet;
11709                    requirer = ps;
11710                }
11711            }
11712        }
11713
11714        if (requiredInstructionSet != null) {
11715            String adjustedAbi;
11716            if (requirer != null) {
11717                // requirer != null implies that either scannedPackage was null or that scannedPackage
11718                // did not require an ABI, in which case we have to adjust scannedPackage to match
11719                // the ABI of the set (which is the same as requirer's ABI)
11720                adjustedAbi = requirer.primaryCpuAbiString;
11721                if (scannedPackage != null) {
11722                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11723                }
11724            } else {
11725                // requirer == null implies that we're updating all ABIs in the set to
11726                // match scannedPackage.
11727                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11728            }
11729
11730            for (PackageSetting ps : packagesForUser) {
11731                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11732                    if (ps.primaryCpuAbiString != null) {
11733                        continue;
11734                    }
11735
11736                    ps.primaryCpuAbiString = adjustedAbi;
11737                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11738                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11739                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11740                        if (DEBUG_ABI_SELECTION) {
11741                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11742                                    + " (requirer="
11743                                    + (requirer != null ? requirer.pkg : "null")
11744                                    + ", scannedPackage="
11745                                    + (scannedPackage != null ? scannedPackage : "null")
11746                                    + ")");
11747                        }
11748                        if (changedAbiCodePath == null) {
11749                            changedAbiCodePath = new ArrayList<>();
11750                        }
11751                        changedAbiCodePath.add(ps.codePathString);
11752                    }
11753                }
11754            }
11755        }
11756        return changedAbiCodePath;
11757    }
11758
11759    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11760        synchronized (mPackages) {
11761            mResolverReplaced = true;
11762            // Set up information for custom user intent resolution activity.
11763            mResolveActivity.applicationInfo = pkg.applicationInfo;
11764            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11765            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11766            mResolveActivity.processName = pkg.applicationInfo.packageName;
11767            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11768            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11769                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11770            mResolveActivity.theme = 0;
11771            mResolveActivity.exported = true;
11772            mResolveActivity.enabled = true;
11773            mResolveInfo.activityInfo = mResolveActivity;
11774            mResolveInfo.priority = 0;
11775            mResolveInfo.preferredOrder = 0;
11776            mResolveInfo.match = 0;
11777            mResolveComponentName = mCustomResolverComponentName;
11778            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11779                    mResolveComponentName);
11780        }
11781    }
11782
11783    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11784        if (installerActivity == null) {
11785            if (DEBUG_INSTANT) {
11786                Slog.d(TAG, "Clear ephemeral installer activity");
11787            }
11788            mInstantAppInstallerActivity = null;
11789            return;
11790        }
11791
11792        if (DEBUG_INSTANT) {
11793            Slog.d(TAG, "Set ephemeral installer activity: "
11794                    + installerActivity.getComponentName());
11795        }
11796        // Set up information for ephemeral installer activity
11797        mInstantAppInstallerActivity = installerActivity;
11798        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11799                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11800        mInstantAppInstallerActivity.exported = true;
11801        mInstantAppInstallerActivity.enabled = true;
11802        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11803        mInstantAppInstallerInfo.priority = 1;
11804        mInstantAppInstallerInfo.preferredOrder = 1;
11805        mInstantAppInstallerInfo.isDefault = true;
11806        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11807                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11808    }
11809
11810    private static String calculateBundledApkRoot(final String codePathString) {
11811        final File codePath = new File(codePathString);
11812        final File codeRoot;
11813        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11814            codeRoot = Environment.getRootDirectory();
11815        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11816            codeRoot = Environment.getOemDirectory();
11817        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11818            codeRoot = Environment.getVendorDirectory();
11819        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11820            codeRoot = Environment.getProductDirectory();
11821        } else {
11822            // Unrecognized code path; take its top real segment as the apk root:
11823            // e.g. /something/app/blah.apk => /something
11824            try {
11825                File f = codePath.getCanonicalFile();
11826                File parent = f.getParentFile();    // non-null because codePath is a file
11827                File tmp;
11828                while ((tmp = parent.getParentFile()) != null) {
11829                    f = parent;
11830                    parent = tmp;
11831                }
11832                codeRoot = f;
11833                Slog.w(TAG, "Unrecognized code path "
11834                        + codePath + " - using " + codeRoot);
11835            } catch (IOException e) {
11836                // Can't canonicalize the code path -- shenanigans?
11837                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11838                return Environment.getRootDirectory().getPath();
11839            }
11840        }
11841        return codeRoot.getPath();
11842    }
11843
11844    /**
11845     * Derive and set the location of native libraries for the given package,
11846     * which varies depending on where and how the package was installed.
11847     */
11848    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11849        final ApplicationInfo info = pkg.applicationInfo;
11850        final String codePath = pkg.codePath;
11851        final File codeFile = new File(codePath);
11852        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11853        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11854
11855        info.nativeLibraryRootDir = null;
11856        info.nativeLibraryRootRequiresIsa = false;
11857        info.nativeLibraryDir = null;
11858        info.secondaryNativeLibraryDir = null;
11859
11860        if (isApkFile(codeFile)) {
11861            // Monolithic install
11862            if (bundledApp) {
11863                // If "/system/lib64/apkname" exists, assume that is the per-package
11864                // native library directory to use; otherwise use "/system/lib/apkname".
11865                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11866                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11867                        getPrimaryInstructionSet(info));
11868
11869                // This is a bundled system app so choose the path based on the ABI.
11870                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11871                // is just the default path.
11872                final String apkName = deriveCodePathName(codePath);
11873                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11874                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11875                        apkName).getAbsolutePath();
11876
11877                if (info.secondaryCpuAbi != null) {
11878                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11879                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11880                            secondaryLibDir, apkName).getAbsolutePath();
11881                }
11882            } else if (asecApp) {
11883                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11884                        .getAbsolutePath();
11885            } else {
11886                final String apkName = deriveCodePathName(codePath);
11887                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11888                        .getAbsolutePath();
11889            }
11890
11891            info.nativeLibraryRootRequiresIsa = false;
11892            info.nativeLibraryDir = info.nativeLibraryRootDir;
11893        } else {
11894            // Cluster install
11895            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11896            info.nativeLibraryRootRequiresIsa = true;
11897
11898            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11899                    getPrimaryInstructionSet(info)).getAbsolutePath();
11900
11901            if (info.secondaryCpuAbi != null) {
11902                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11903                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11904            }
11905        }
11906    }
11907
11908    /**
11909     * Calculate the abis and roots for a bundled app. These can uniquely
11910     * be determined from the contents of the system partition, i.e whether
11911     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11912     * of this information, and instead assume that the system was built
11913     * sensibly.
11914     */
11915    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11916                                           PackageSetting pkgSetting) {
11917        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11918
11919        // If "/system/lib64/apkname" exists, assume that is the per-package
11920        // native library directory to use; otherwise use "/system/lib/apkname".
11921        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11922        setBundledAppAbi(pkg, apkRoot, apkName);
11923        // pkgSetting might be null during rescan following uninstall of updates
11924        // to a bundled app, so accommodate that possibility.  The settings in
11925        // that case will be established later from the parsed package.
11926        //
11927        // If the settings aren't null, sync them up with what we've just derived.
11928        // note that apkRoot isn't stored in the package settings.
11929        if (pkgSetting != null) {
11930            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11931            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11932        }
11933    }
11934
11935    /**
11936     * Deduces the ABI of a bundled app and sets the relevant fields on the
11937     * parsed pkg object.
11938     *
11939     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11940     *        under which system libraries are installed.
11941     * @param apkName the name of the installed package.
11942     */
11943    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11944        final File codeFile = new File(pkg.codePath);
11945
11946        final boolean has64BitLibs;
11947        final boolean has32BitLibs;
11948        if (isApkFile(codeFile)) {
11949            // Monolithic install
11950            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11951            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11952        } else {
11953            // Cluster install
11954            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11955            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11956                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11957                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11958                has64BitLibs = (new File(rootDir, isa)).exists();
11959            } else {
11960                has64BitLibs = false;
11961            }
11962            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11963                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11964                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11965                has32BitLibs = (new File(rootDir, isa)).exists();
11966            } else {
11967                has32BitLibs = false;
11968            }
11969        }
11970
11971        if (has64BitLibs && !has32BitLibs) {
11972            // The package has 64 bit libs, but not 32 bit libs. Its primary
11973            // ABI should be 64 bit. We can safely assume here that the bundled
11974            // native libraries correspond to the most preferred ABI in the list.
11975
11976            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11977            pkg.applicationInfo.secondaryCpuAbi = null;
11978        } else if (has32BitLibs && !has64BitLibs) {
11979            // The package has 32 bit libs but not 64 bit libs. Its primary
11980            // ABI should be 32 bit.
11981
11982            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11983            pkg.applicationInfo.secondaryCpuAbi = null;
11984        } else if (has32BitLibs && has64BitLibs) {
11985            // The application has both 64 and 32 bit bundled libraries. We check
11986            // here that the app declares multiArch support, and warn if it doesn't.
11987            //
11988            // We will be lenient here and record both ABIs. The primary will be the
11989            // ABI that's higher on the list, i.e, a device that's configured to prefer
11990            // 64 bit apps will see a 64 bit primary ABI,
11991
11992            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11993                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11994            }
11995
11996            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11997                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11998                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11999            } else {
12000                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12001                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12002            }
12003        } else {
12004            pkg.applicationInfo.primaryCpuAbi = null;
12005            pkg.applicationInfo.secondaryCpuAbi = null;
12006        }
12007    }
12008
12009    private void killApplication(String pkgName, int appId, String reason) {
12010        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12011    }
12012
12013    private void killApplication(String pkgName, int appId, int userId, String reason) {
12014        // Request the ActivityManager to kill the process(only for existing packages)
12015        // so that we do not end up in a confused state while the user is still using the older
12016        // version of the application while the new one gets installed.
12017        final long token = Binder.clearCallingIdentity();
12018        try {
12019            IActivityManager am = ActivityManager.getService();
12020            if (am != null) {
12021                try {
12022                    am.killApplication(pkgName, appId, userId, reason);
12023                } catch (RemoteException e) {
12024                }
12025            }
12026        } finally {
12027            Binder.restoreCallingIdentity(token);
12028        }
12029    }
12030
12031    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12032        // Remove the parent package setting
12033        PackageSetting ps = (PackageSetting) pkg.mExtras;
12034        if (ps != null) {
12035            removePackageLI(ps, chatty);
12036        }
12037        // Remove the child package setting
12038        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12039        for (int i = 0; i < childCount; i++) {
12040            PackageParser.Package childPkg = pkg.childPackages.get(i);
12041            ps = (PackageSetting) childPkg.mExtras;
12042            if (ps != null) {
12043                removePackageLI(ps, chatty);
12044            }
12045        }
12046    }
12047
12048    void removePackageLI(PackageSetting ps, boolean chatty) {
12049        if (DEBUG_INSTALL) {
12050            if (chatty)
12051                Log.d(TAG, "Removing package " + ps.name);
12052        }
12053
12054        // writer
12055        synchronized (mPackages) {
12056            mPackages.remove(ps.name);
12057            final PackageParser.Package pkg = ps.pkg;
12058            if (pkg != null) {
12059                cleanPackageDataStructuresLILPw(pkg, chatty);
12060            }
12061        }
12062    }
12063
12064    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12065        if (DEBUG_INSTALL) {
12066            if (chatty)
12067                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12068        }
12069
12070        // writer
12071        synchronized (mPackages) {
12072            // Remove the parent package
12073            mPackages.remove(pkg.applicationInfo.packageName);
12074            cleanPackageDataStructuresLILPw(pkg, chatty);
12075
12076            // Remove the child packages
12077            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12078            for (int i = 0; i < childCount; i++) {
12079                PackageParser.Package childPkg = pkg.childPackages.get(i);
12080                mPackages.remove(childPkg.applicationInfo.packageName);
12081                cleanPackageDataStructuresLILPw(childPkg, chatty);
12082            }
12083        }
12084    }
12085
12086    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12087        int N = pkg.providers.size();
12088        StringBuilder r = null;
12089        int i;
12090        for (i=0; i<N; i++) {
12091            PackageParser.Provider p = pkg.providers.get(i);
12092            mProviders.removeProvider(p);
12093            if (p.info.authority == null) {
12094
12095                /* There was another ContentProvider with this authority when
12096                 * this app was installed so this authority is null,
12097                 * Ignore it as we don't have to unregister the provider.
12098                 */
12099                continue;
12100            }
12101            String names[] = p.info.authority.split(";");
12102            for (int j = 0; j < names.length; j++) {
12103                if (mProvidersByAuthority.get(names[j]) == p) {
12104                    mProvidersByAuthority.remove(names[j]);
12105                    if (DEBUG_REMOVE) {
12106                        if (chatty)
12107                            Log.d(TAG, "Unregistered content provider: " + names[j]
12108                                    + ", className = " + p.info.name + ", isSyncable = "
12109                                    + p.info.isSyncable);
12110                    }
12111                }
12112            }
12113            if (DEBUG_REMOVE && chatty) {
12114                if (r == null) {
12115                    r = new StringBuilder(256);
12116                } else {
12117                    r.append(' ');
12118                }
12119                r.append(p.info.name);
12120            }
12121        }
12122        if (r != null) {
12123            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12124        }
12125
12126        N = pkg.services.size();
12127        r = null;
12128        for (i=0; i<N; i++) {
12129            PackageParser.Service s = pkg.services.get(i);
12130            mServices.removeService(s);
12131            if (chatty) {
12132                if (r == null) {
12133                    r = new StringBuilder(256);
12134                } else {
12135                    r.append(' ');
12136                }
12137                r.append(s.info.name);
12138            }
12139        }
12140        if (r != null) {
12141            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12142        }
12143
12144        N = pkg.receivers.size();
12145        r = null;
12146        for (i=0; i<N; i++) {
12147            PackageParser.Activity a = pkg.receivers.get(i);
12148            mReceivers.removeActivity(a, "receiver");
12149            if (DEBUG_REMOVE && chatty) {
12150                if (r == null) {
12151                    r = new StringBuilder(256);
12152                } else {
12153                    r.append(' ');
12154                }
12155                r.append(a.info.name);
12156            }
12157        }
12158        if (r != null) {
12159            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12160        }
12161
12162        N = pkg.activities.size();
12163        r = null;
12164        for (i=0; i<N; i++) {
12165            PackageParser.Activity a = pkg.activities.get(i);
12166            mActivities.removeActivity(a, "activity");
12167            if (DEBUG_REMOVE && chatty) {
12168                if (r == null) {
12169                    r = new StringBuilder(256);
12170                } else {
12171                    r.append(' ');
12172                }
12173                r.append(a.info.name);
12174            }
12175        }
12176        if (r != null) {
12177            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12178        }
12179
12180        mPermissionManager.removeAllPermissions(pkg, chatty);
12181
12182        N = pkg.instrumentation.size();
12183        r = null;
12184        for (i=0; i<N; i++) {
12185            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12186            mInstrumentation.remove(a.getComponentName());
12187            if (DEBUG_REMOVE && chatty) {
12188                if (r == null) {
12189                    r = new StringBuilder(256);
12190                } else {
12191                    r.append(' ');
12192                }
12193                r.append(a.info.name);
12194            }
12195        }
12196        if (r != null) {
12197            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12198        }
12199
12200        r = null;
12201        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12202            // Only system apps can hold shared libraries.
12203            if (pkg.libraryNames != null) {
12204                for (i = 0; i < pkg.libraryNames.size(); i++) {
12205                    String name = pkg.libraryNames.get(i);
12206                    if (removeSharedLibraryLPw(name, 0)) {
12207                        if (DEBUG_REMOVE && chatty) {
12208                            if (r == null) {
12209                                r = new StringBuilder(256);
12210                            } else {
12211                                r.append(' ');
12212                            }
12213                            r.append(name);
12214                        }
12215                    }
12216                }
12217            }
12218        }
12219
12220        r = null;
12221
12222        // Any package can hold static shared libraries.
12223        if (pkg.staticSharedLibName != null) {
12224            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12225                if (DEBUG_REMOVE && chatty) {
12226                    if (r == null) {
12227                        r = new StringBuilder(256);
12228                    } else {
12229                        r.append(' ');
12230                    }
12231                    r.append(pkg.staticSharedLibName);
12232                }
12233            }
12234        }
12235
12236        if (r != null) {
12237            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12238        }
12239    }
12240
12241
12242    final class ActivityIntentResolver
12243            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12244        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12245                boolean defaultOnly, int userId) {
12246            if (!sUserManager.exists(userId)) return null;
12247            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12248            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12249        }
12250
12251        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12252                int userId) {
12253            if (!sUserManager.exists(userId)) return null;
12254            mFlags = flags;
12255            return super.queryIntent(intent, resolvedType,
12256                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12257                    userId);
12258        }
12259
12260        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12261                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12262            if (!sUserManager.exists(userId)) return null;
12263            if (packageActivities == null) {
12264                return null;
12265            }
12266            mFlags = flags;
12267            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12268            final int N = packageActivities.size();
12269            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12270                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12271
12272            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12273            for (int i = 0; i < N; ++i) {
12274                intentFilters = packageActivities.get(i).intents;
12275                if (intentFilters != null && intentFilters.size() > 0) {
12276                    PackageParser.ActivityIntentInfo[] array =
12277                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12278                    intentFilters.toArray(array);
12279                    listCut.add(array);
12280                }
12281            }
12282            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12283        }
12284
12285        /**
12286         * Finds a privileged activity that matches the specified activity names.
12287         */
12288        private PackageParser.Activity findMatchingActivity(
12289                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12290            for (PackageParser.Activity sysActivity : activityList) {
12291                if (sysActivity.info.name.equals(activityInfo.name)) {
12292                    return sysActivity;
12293                }
12294                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12295                    return sysActivity;
12296                }
12297                if (sysActivity.info.targetActivity != null) {
12298                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12299                        return sysActivity;
12300                    }
12301                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12302                        return sysActivity;
12303                    }
12304                }
12305            }
12306            return null;
12307        }
12308
12309        public class IterGenerator<E> {
12310            public Iterator<E> generate(ActivityIntentInfo info) {
12311                return null;
12312            }
12313        }
12314
12315        public class ActionIterGenerator extends IterGenerator<String> {
12316            @Override
12317            public Iterator<String> generate(ActivityIntentInfo info) {
12318                return info.actionsIterator();
12319            }
12320        }
12321
12322        public class CategoriesIterGenerator extends IterGenerator<String> {
12323            @Override
12324            public Iterator<String> generate(ActivityIntentInfo info) {
12325                return info.categoriesIterator();
12326            }
12327        }
12328
12329        public class SchemesIterGenerator extends IterGenerator<String> {
12330            @Override
12331            public Iterator<String> generate(ActivityIntentInfo info) {
12332                return info.schemesIterator();
12333            }
12334        }
12335
12336        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12337            @Override
12338            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12339                return info.authoritiesIterator();
12340            }
12341        }
12342
12343        /**
12344         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12345         * MODIFIED. Do not pass in a list that should not be changed.
12346         */
12347        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12348                IterGenerator<T> generator, Iterator<T> searchIterator) {
12349            // loop through the set of actions; every one must be found in the intent filter
12350            while (searchIterator.hasNext()) {
12351                // we must have at least one filter in the list to consider a match
12352                if (intentList.size() == 0) {
12353                    break;
12354                }
12355
12356                final T searchAction = searchIterator.next();
12357
12358                // loop through the set of intent filters
12359                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12360                while (intentIter.hasNext()) {
12361                    final ActivityIntentInfo intentInfo = intentIter.next();
12362                    boolean selectionFound = false;
12363
12364                    // loop through the intent filter's selection criteria; at least one
12365                    // of them must match the searched criteria
12366                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12367                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12368                        final T intentSelection = intentSelectionIter.next();
12369                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12370                            selectionFound = true;
12371                            break;
12372                        }
12373                    }
12374
12375                    // the selection criteria wasn't found in this filter's set; this filter
12376                    // is not a potential match
12377                    if (!selectionFound) {
12378                        intentIter.remove();
12379                    }
12380                }
12381            }
12382        }
12383
12384        private boolean isProtectedAction(ActivityIntentInfo filter) {
12385            final Iterator<String> actionsIter = filter.actionsIterator();
12386            while (actionsIter != null && actionsIter.hasNext()) {
12387                final String filterAction = actionsIter.next();
12388                if (PROTECTED_ACTIONS.contains(filterAction)) {
12389                    return true;
12390                }
12391            }
12392            return false;
12393        }
12394
12395        /**
12396         * Adjusts the priority of the given intent filter according to policy.
12397         * <p>
12398         * <ul>
12399         * <li>The priority for non privileged applications is capped to '0'</li>
12400         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12401         * <li>The priority for unbundled updates to privileged applications is capped to the
12402         *      priority defined on the system partition</li>
12403         * </ul>
12404         * <p>
12405         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12406         * allowed to obtain any priority on any action.
12407         */
12408        private void adjustPriority(
12409                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12410            // nothing to do; priority is fine as-is
12411            if (intent.getPriority() <= 0) {
12412                return;
12413            }
12414
12415            final ActivityInfo activityInfo = intent.activity.info;
12416            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12417
12418            final boolean privilegedApp =
12419                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12420            if (!privilegedApp) {
12421                // non-privileged applications can never define a priority >0
12422                if (DEBUG_FILTERS) {
12423                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12424                            + " package: " + applicationInfo.packageName
12425                            + " activity: " + intent.activity.className
12426                            + " origPrio: " + intent.getPriority());
12427                }
12428                intent.setPriority(0);
12429                return;
12430            }
12431
12432            if (systemActivities == null) {
12433                // the system package is not disabled; we're parsing the system partition
12434                if (isProtectedAction(intent)) {
12435                    if (mDeferProtectedFilters) {
12436                        // We can't deal with these just yet. No component should ever obtain a
12437                        // >0 priority for a protected actions, with ONE exception -- the setup
12438                        // wizard. The setup wizard, however, cannot be known until we're able to
12439                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12440                        // until all intent filters have been processed. Chicken, meet egg.
12441                        // Let the filter temporarily have a high priority and rectify the
12442                        // priorities after all system packages have been scanned.
12443                        mProtectedFilters.add(intent);
12444                        if (DEBUG_FILTERS) {
12445                            Slog.i(TAG, "Protected action; save for later;"
12446                                    + " package: " + applicationInfo.packageName
12447                                    + " activity: " + intent.activity.className
12448                                    + " origPrio: " + intent.getPriority());
12449                        }
12450                        return;
12451                    } else {
12452                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12453                            Slog.i(TAG, "No setup wizard;"
12454                                + " All protected intents capped to priority 0");
12455                        }
12456                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12457                            if (DEBUG_FILTERS) {
12458                                Slog.i(TAG, "Found setup wizard;"
12459                                    + " allow priority " + intent.getPriority() + ";"
12460                                    + " package: " + intent.activity.info.packageName
12461                                    + " activity: " + intent.activity.className
12462                                    + " priority: " + intent.getPriority());
12463                            }
12464                            // setup wizard gets whatever it wants
12465                            return;
12466                        }
12467                        if (DEBUG_FILTERS) {
12468                            Slog.i(TAG, "Protected action; cap priority to 0;"
12469                                    + " package: " + intent.activity.info.packageName
12470                                    + " activity: " + intent.activity.className
12471                                    + " origPrio: " + intent.getPriority());
12472                        }
12473                        intent.setPriority(0);
12474                        return;
12475                    }
12476                }
12477                // privileged apps on the system image get whatever priority they request
12478                return;
12479            }
12480
12481            // privileged app unbundled update ... try to find the same activity
12482            final PackageParser.Activity foundActivity =
12483                    findMatchingActivity(systemActivities, activityInfo);
12484            if (foundActivity == null) {
12485                // this is a new activity; it cannot obtain >0 priority
12486                if (DEBUG_FILTERS) {
12487                    Slog.i(TAG, "New activity; cap priority to 0;"
12488                            + " package: " + applicationInfo.packageName
12489                            + " activity: " + intent.activity.className
12490                            + " origPrio: " + intent.getPriority());
12491                }
12492                intent.setPriority(0);
12493                return;
12494            }
12495
12496            // found activity, now check for filter equivalence
12497
12498            // a shallow copy is enough; we modify the list, not its contents
12499            final List<ActivityIntentInfo> intentListCopy =
12500                    new ArrayList<>(foundActivity.intents);
12501            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12502
12503            // find matching action subsets
12504            final Iterator<String> actionsIterator = intent.actionsIterator();
12505            if (actionsIterator != null) {
12506                getIntentListSubset(
12507                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12508                if (intentListCopy.size() == 0) {
12509                    // no more intents to match; we're not equivalent
12510                    if (DEBUG_FILTERS) {
12511                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12512                                + " package: " + applicationInfo.packageName
12513                                + " activity: " + intent.activity.className
12514                                + " origPrio: " + intent.getPriority());
12515                    }
12516                    intent.setPriority(0);
12517                    return;
12518                }
12519            }
12520
12521            // find matching category subsets
12522            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12523            if (categoriesIterator != null) {
12524                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12525                        categoriesIterator);
12526                if (intentListCopy.size() == 0) {
12527                    // no more intents to match; we're not equivalent
12528                    if (DEBUG_FILTERS) {
12529                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12530                                + " package: " + applicationInfo.packageName
12531                                + " activity: " + intent.activity.className
12532                                + " origPrio: " + intent.getPriority());
12533                    }
12534                    intent.setPriority(0);
12535                    return;
12536                }
12537            }
12538
12539            // find matching schemes subsets
12540            final Iterator<String> schemesIterator = intent.schemesIterator();
12541            if (schemesIterator != null) {
12542                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12543                        schemesIterator);
12544                if (intentListCopy.size() == 0) {
12545                    // no more intents to match; we're not equivalent
12546                    if (DEBUG_FILTERS) {
12547                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12548                                + " package: " + applicationInfo.packageName
12549                                + " activity: " + intent.activity.className
12550                                + " origPrio: " + intent.getPriority());
12551                    }
12552                    intent.setPriority(0);
12553                    return;
12554                }
12555            }
12556
12557            // find matching authorities subsets
12558            final Iterator<IntentFilter.AuthorityEntry>
12559                    authoritiesIterator = intent.authoritiesIterator();
12560            if (authoritiesIterator != null) {
12561                getIntentListSubset(intentListCopy,
12562                        new AuthoritiesIterGenerator(),
12563                        authoritiesIterator);
12564                if (intentListCopy.size() == 0) {
12565                    // no more intents to match; we're not equivalent
12566                    if (DEBUG_FILTERS) {
12567                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12568                                + " package: " + applicationInfo.packageName
12569                                + " activity: " + intent.activity.className
12570                                + " origPrio: " + intent.getPriority());
12571                    }
12572                    intent.setPriority(0);
12573                    return;
12574                }
12575            }
12576
12577            // we found matching filter(s); app gets the max priority of all intents
12578            int cappedPriority = 0;
12579            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12580                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12581            }
12582            if (intent.getPriority() > cappedPriority) {
12583                if (DEBUG_FILTERS) {
12584                    Slog.i(TAG, "Found matching filter(s);"
12585                            + " cap priority to " + cappedPriority + ";"
12586                            + " package: " + applicationInfo.packageName
12587                            + " activity: " + intent.activity.className
12588                            + " origPrio: " + intent.getPriority());
12589                }
12590                intent.setPriority(cappedPriority);
12591                return;
12592            }
12593            // all this for nothing; the requested priority was <= what was on the system
12594        }
12595
12596        public final void addActivity(PackageParser.Activity a, String type) {
12597            mActivities.put(a.getComponentName(), a);
12598            if (DEBUG_SHOW_INFO)
12599                Log.v(
12600                TAG, "  " + type + " " +
12601                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12602            if (DEBUG_SHOW_INFO)
12603                Log.v(TAG, "    Class=" + a.info.name);
12604            final int NI = a.intents.size();
12605            for (int j=0; j<NI; j++) {
12606                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12607                if ("activity".equals(type)) {
12608                    final PackageSetting ps =
12609                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12610                    final List<PackageParser.Activity> systemActivities =
12611                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12612                    adjustPriority(systemActivities, intent);
12613                }
12614                if (DEBUG_SHOW_INFO) {
12615                    Log.v(TAG, "    IntentFilter:");
12616                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12617                }
12618                if (!intent.debugCheck()) {
12619                    Log.w(TAG, "==> For Activity " + a.info.name);
12620                }
12621                addFilter(intent);
12622            }
12623        }
12624
12625        public final void removeActivity(PackageParser.Activity a, String type) {
12626            mActivities.remove(a.getComponentName());
12627            if (DEBUG_SHOW_INFO) {
12628                Log.v(TAG, "  " + type + " "
12629                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12630                                : a.info.name) + ":");
12631                Log.v(TAG, "    Class=" + a.info.name);
12632            }
12633            final int NI = a.intents.size();
12634            for (int j=0; j<NI; j++) {
12635                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12636                if (DEBUG_SHOW_INFO) {
12637                    Log.v(TAG, "    IntentFilter:");
12638                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12639                }
12640                removeFilter(intent);
12641            }
12642        }
12643
12644        @Override
12645        protected boolean allowFilterResult(
12646                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12647            ActivityInfo filterAi = filter.activity.info;
12648            for (int i=dest.size()-1; i>=0; i--) {
12649                ActivityInfo destAi = dest.get(i).activityInfo;
12650                if (destAi.name == filterAi.name
12651                        && destAi.packageName == filterAi.packageName) {
12652                    return false;
12653                }
12654            }
12655            return true;
12656        }
12657
12658        @Override
12659        protected ActivityIntentInfo[] newArray(int size) {
12660            return new ActivityIntentInfo[size];
12661        }
12662
12663        @Override
12664        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12665            if (!sUserManager.exists(userId)) return true;
12666            PackageParser.Package p = filter.activity.owner;
12667            if (p != null) {
12668                PackageSetting ps = (PackageSetting)p.mExtras;
12669                if (ps != null) {
12670                    // System apps are never considered stopped for purposes of
12671                    // filtering, because there may be no way for the user to
12672                    // actually re-launch them.
12673                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12674                            && ps.getStopped(userId);
12675                }
12676            }
12677            return false;
12678        }
12679
12680        @Override
12681        protected boolean isPackageForFilter(String packageName,
12682                PackageParser.ActivityIntentInfo info) {
12683            return packageName.equals(info.activity.owner.packageName);
12684        }
12685
12686        @Override
12687        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12688                int match, int userId) {
12689            if (!sUserManager.exists(userId)) return null;
12690            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12691                return null;
12692            }
12693            final PackageParser.Activity activity = info.activity;
12694            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12695            if (ps == null) {
12696                return null;
12697            }
12698            final PackageUserState userState = ps.readUserState(userId);
12699            ActivityInfo ai =
12700                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12701            if (ai == null) {
12702                return null;
12703            }
12704            final boolean matchExplicitlyVisibleOnly =
12705                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12706            final boolean matchVisibleToInstantApp =
12707                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12708            final boolean componentVisible =
12709                    matchVisibleToInstantApp
12710                    && info.isVisibleToInstantApp()
12711                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12712            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12713            // throw out filters that aren't visible to ephemeral apps
12714            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12715                return null;
12716            }
12717            // throw out instant app filters if we're not explicitly requesting them
12718            if (!matchInstantApp && userState.instantApp) {
12719                return null;
12720            }
12721            // throw out instant app filters if updates are available; will trigger
12722            // instant app resolution
12723            if (userState.instantApp && ps.isUpdateAvailable()) {
12724                return null;
12725            }
12726            final ResolveInfo res = new ResolveInfo();
12727            res.activityInfo = ai;
12728            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12729                res.filter = info;
12730            }
12731            if (info != null) {
12732                res.handleAllWebDataURI = info.handleAllWebDataURI();
12733            }
12734            res.priority = info.getPriority();
12735            res.preferredOrder = activity.owner.mPreferredOrder;
12736            //System.out.println("Result: " + res.activityInfo.className +
12737            //                   " = " + res.priority);
12738            res.match = match;
12739            res.isDefault = info.hasDefault;
12740            res.labelRes = info.labelRes;
12741            res.nonLocalizedLabel = info.nonLocalizedLabel;
12742            if (userNeedsBadging(userId)) {
12743                res.noResourceId = true;
12744            } else {
12745                res.icon = info.icon;
12746            }
12747            res.iconResourceId = info.icon;
12748            res.system = res.activityInfo.applicationInfo.isSystemApp();
12749            res.isInstantAppAvailable = userState.instantApp;
12750            return res;
12751        }
12752
12753        @Override
12754        protected void sortResults(List<ResolveInfo> results) {
12755            Collections.sort(results, mResolvePrioritySorter);
12756        }
12757
12758        @Override
12759        protected void dumpFilter(PrintWriter out, String prefix,
12760                PackageParser.ActivityIntentInfo filter) {
12761            out.print(prefix); out.print(
12762                    Integer.toHexString(System.identityHashCode(filter.activity)));
12763                    out.print(' ');
12764                    filter.activity.printComponentShortName(out);
12765                    out.print(" filter ");
12766                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12767        }
12768
12769        @Override
12770        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12771            return filter.activity;
12772        }
12773
12774        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12775            PackageParser.Activity activity = (PackageParser.Activity)label;
12776            out.print(prefix); out.print(
12777                    Integer.toHexString(System.identityHashCode(activity)));
12778                    out.print(' ');
12779                    activity.printComponentShortName(out);
12780            if (count > 1) {
12781                out.print(" ("); out.print(count); out.print(" filters)");
12782            }
12783            out.println();
12784        }
12785
12786        // Keys are String (activity class name), values are Activity.
12787        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12788                = new ArrayMap<ComponentName, PackageParser.Activity>();
12789        private int mFlags;
12790    }
12791
12792    private final class ServiceIntentResolver
12793            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12794        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12795                boolean defaultOnly, int userId) {
12796            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12797            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12798        }
12799
12800        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12801                int userId) {
12802            if (!sUserManager.exists(userId)) return null;
12803            mFlags = flags;
12804            return super.queryIntent(intent, resolvedType,
12805                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12806                    userId);
12807        }
12808
12809        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12810                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12811            if (!sUserManager.exists(userId)) return null;
12812            if (packageServices == null) {
12813                return null;
12814            }
12815            mFlags = flags;
12816            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12817            final int N = packageServices.size();
12818            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12819                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12820
12821            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12822            for (int i = 0; i < N; ++i) {
12823                intentFilters = packageServices.get(i).intents;
12824                if (intentFilters != null && intentFilters.size() > 0) {
12825                    PackageParser.ServiceIntentInfo[] array =
12826                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12827                    intentFilters.toArray(array);
12828                    listCut.add(array);
12829                }
12830            }
12831            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12832        }
12833
12834        public final void addService(PackageParser.Service s) {
12835            mServices.put(s.getComponentName(), s);
12836            if (DEBUG_SHOW_INFO) {
12837                Log.v(TAG, "  "
12838                        + (s.info.nonLocalizedLabel != null
12839                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12840                Log.v(TAG, "    Class=" + s.info.name);
12841            }
12842            final int NI = s.intents.size();
12843            int j;
12844            for (j=0; j<NI; j++) {
12845                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12846                if (DEBUG_SHOW_INFO) {
12847                    Log.v(TAG, "    IntentFilter:");
12848                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12849                }
12850                if (!intent.debugCheck()) {
12851                    Log.w(TAG, "==> For Service " + s.info.name);
12852                }
12853                addFilter(intent);
12854            }
12855        }
12856
12857        public final void removeService(PackageParser.Service s) {
12858            mServices.remove(s.getComponentName());
12859            if (DEBUG_SHOW_INFO) {
12860                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12861                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12862                Log.v(TAG, "    Class=" + s.info.name);
12863            }
12864            final int NI = s.intents.size();
12865            int j;
12866            for (j=0; j<NI; j++) {
12867                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12868                if (DEBUG_SHOW_INFO) {
12869                    Log.v(TAG, "    IntentFilter:");
12870                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12871                }
12872                removeFilter(intent);
12873            }
12874        }
12875
12876        @Override
12877        protected boolean allowFilterResult(
12878                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12879            ServiceInfo filterSi = filter.service.info;
12880            for (int i=dest.size()-1; i>=0; i--) {
12881                ServiceInfo destAi = dest.get(i).serviceInfo;
12882                if (destAi.name == filterSi.name
12883                        && destAi.packageName == filterSi.packageName) {
12884                    return false;
12885                }
12886            }
12887            return true;
12888        }
12889
12890        @Override
12891        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12892            return new PackageParser.ServiceIntentInfo[size];
12893        }
12894
12895        @Override
12896        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12897            if (!sUserManager.exists(userId)) return true;
12898            PackageParser.Package p = filter.service.owner;
12899            if (p != null) {
12900                PackageSetting ps = (PackageSetting)p.mExtras;
12901                if (ps != null) {
12902                    // System apps are never considered stopped for purposes of
12903                    // filtering, because there may be no way for the user to
12904                    // actually re-launch them.
12905                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12906                            && ps.getStopped(userId);
12907                }
12908            }
12909            return false;
12910        }
12911
12912        @Override
12913        protected boolean isPackageForFilter(String packageName,
12914                PackageParser.ServiceIntentInfo info) {
12915            return packageName.equals(info.service.owner.packageName);
12916        }
12917
12918        @Override
12919        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12920                int match, int userId) {
12921            if (!sUserManager.exists(userId)) return null;
12922            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12923            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12924                return null;
12925            }
12926            final PackageParser.Service service = info.service;
12927            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12928            if (ps == null) {
12929                return null;
12930            }
12931            final PackageUserState userState = ps.readUserState(userId);
12932            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12933                    userState, userId);
12934            if (si == null) {
12935                return null;
12936            }
12937            final boolean matchVisibleToInstantApp =
12938                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12939            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12940            // throw out filters that aren't visible to ephemeral apps
12941            if (matchVisibleToInstantApp
12942                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12943                return null;
12944            }
12945            // throw out ephemeral filters if we're not explicitly requesting them
12946            if (!isInstantApp && userState.instantApp) {
12947                return null;
12948            }
12949            // throw out instant app filters if updates are available; will trigger
12950            // instant app resolution
12951            if (userState.instantApp && ps.isUpdateAvailable()) {
12952                return null;
12953            }
12954            final ResolveInfo res = new ResolveInfo();
12955            res.serviceInfo = si;
12956            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12957                res.filter = filter;
12958            }
12959            res.priority = info.getPriority();
12960            res.preferredOrder = service.owner.mPreferredOrder;
12961            res.match = match;
12962            res.isDefault = info.hasDefault;
12963            res.labelRes = info.labelRes;
12964            res.nonLocalizedLabel = info.nonLocalizedLabel;
12965            res.icon = info.icon;
12966            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12967            return res;
12968        }
12969
12970        @Override
12971        protected void sortResults(List<ResolveInfo> results) {
12972            Collections.sort(results, mResolvePrioritySorter);
12973        }
12974
12975        @Override
12976        protected void dumpFilter(PrintWriter out, String prefix,
12977                PackageParser.ServiceIntentInfo filter) {
12978            out.print(prefix); out.print(
12979                    Integer.toHexString(System.identityHashCode(filter.service)));
12980                    out.print(' ');
12981                    filter.service.printComponentShortName(out);
12982                    out.print(" filter ");
12983                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12984                    if (filter.service.info.permission != null) {
12985                        out.print(" permission "); out.println(filter.service.info.permission);
12986                    } else {
12987                        out.println();
12988                    }
12989        }
12990
12991        @Override
12992        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12993            return filter.service;
12994        }
12995
12996        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12997            PackageParser.Service service = (PackageParser.Service)label;
12998            out.print(prefix); out.print(
12999                    Integer.toHexString(System.identityHashCode(service)));
13000                    out.print(' ');
13001                    service.printComponentShortName(out);
13002            if (count > 1) {
13003                out.print(" ("); out.print(count); out.print(" filters)");
13004            }
13005            out.println();
13006        }
13007
13008//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13009//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13010//            final List<ResolveInfo> retList = Lists.newArrayList();
13011//            while (i.hasNext()) {
13012//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13013//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13014//                    retList.add(resolveInfo);
13015//                }
13016//            }
13017//            return retList;
13018//        }
13019
13020        // Keys are String (activity class name), values are Activity.
13021        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13022                = new ArrayMap<ComponentName, PackageParser.Service>();
13023        private int mFlags;
13024    }
13025
13026    private final class ProviderIntentResolver
13027            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13028        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13029                boolean defaultOnly, int userId) {
13030            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13031            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13032        }
13033
13034        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13035                int userId) {
13036            if (!sUserManager.exists(userId))
13037                return null;
13038            mFlags = flags;
13039            return super.queryIntent(intent, resolvedType,
13040                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13041                    userId);
13042        }
13043
13044        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13045                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13046            if (!sUserManager.exists(userId))
13047                return null;
13048            if (packageProviders == null) {
13049                return null;
13050            }
13051            mFlags = flags;
13052            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13053            final int N = packageProviders.size();
13054            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13055                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13056
13057            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13058            for (int i = 0; i < N; ++i) {
13059                intentFilters = packageProviders.get(i).intents;
13060                if (intentFilters != null && intentFilters.size() > 0) {
13061                    PackageParser.ProviderIntentInfo[] array =
13062                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13063                    intentFilters.toArray(array);
13064                    listCut.add(array);
13065                }
13066            }
13067            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13068        }
13069
13070        public final void addProvider(PackageParser.Provider p) {
13071            if (mProviders.containsKey(p.getComponentName())) {
13072                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13073                return;
13074            }
13075
13076            mProviders.put(p.getComponentName(), p);
13077            if (DEBUG_SHOW_INFO) {
13078                Log.v(TAG, "  "
13079                        + (p.info.nonLocalizedLabel != null
13080                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13081                Log.v(TAG, "    Class=" + p.info.name);
13082            }
13083            final int NI = p.intents.size();
13084            int j;
13085            for (j = 0; j < NI; j++) {
13086                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13087                if (DEBUG_SHOW_INFO) {
13088                    Log.v(TAG, "    IntentFilter:");
13089                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13090                }
13091                if (!intent.debugCheck()) {
13092                    Log.w(TAG, "==> For Provider " + p.info.name);
13093                }
13094                addFilter(intent);
13095            }
13096        }
13097
13098        public final void removeProvider(PackageParser.Provider p) {
13099            mProviders.remove(p.getComponentName());
13100            if (DEBUG_SHOW_INFO) {
13101                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13102                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13103                Log.v(TAG, "    Class=" + p.info.name);
13104            }
13105            final int NI = p.intents.size();
13106            int j;
13107            for (j = 0; j < NI; j++) {
13108                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13109                if (DEBUG_SHOW_INFO) {
13110                    Log.v(TAG, "    IntentFilter:");
13111                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13112                }
13113                removeFilter(intent);
13114            }
13115        }
13116
13117        @Override
13118        protected boolean allowFilterResult(
13119                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13120            ProviderInfo filterPi = filter.provider.info;
13121            for (int i = dest.size() - 1; i >= 0; i--) {
13122                ProviderInfo destPi = dest.get(i).providerInfo;
13123                if (destPi.name == filterPi.name
13124                        && destPi.packageName == filterPi.packageName) {
13125                    return false;
13126                }
13127            }
13128            return true;
13129        }
13130
13131        @Override
13132        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13133            return new PackageParser.ProviderIntentInfo[size];
13134        }
13135
13136        @Override
13137        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13138            if (!sUserManager.exists(userId))
13139                return true;
13140            PackageParser.Package p = filter.provider.owner;
13141            if (p != null) {
13142                PackageSetting ps = (PackageSetting) p.mExtras;
13143                if (ps != null) {
13144                    // System apps are never considered stopped for purposes of
13145                    // filtering, because there may be no way for the user to
13146                    // actually re-launch them.
13147                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13148                            && ps.getStopped(userId);
13149                }
13150            }
13151            return false;
13152        }
13153
13154        @Override
13155        protected boolean isPackageForFilter(String packageName,
13156                PackageParser.ProviderIntentInfo info) {
13157            return packageName.equals(info.provider.owner.packageName);
13158        }
13159
13160        @Override
13161        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13162                int match, int userId) {
13163            if (!sUserManager.exists(userId))
13164                return null;
13165            final PackageParser.ProviderIntentInfo info = filter;
13166            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13167                return null;
13168            }
13169            final PackageParser.Provider provider = info.provider;
13170            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13171            if (ps == null) {
13172                return null;
13173            }
13174            final PackageUserState userState = ps.readUserState(userId);
13175            final boolean matchVisibleToInstantApp =
13176                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13177            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13178            // throw out filters that aren't visible to instant applications
13179            if (matchVisibleToInstantApp
13180                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13181                return null;
13182            }
13183            // throw out instant application filters if we're not explicitly requesting them
13184            if (!isInstantApp && userState.instantApp) {
13185                return null;
13186            }
13187            // throw out instant application filters if updates are available; will trigger
13188            // instant application resolution
13189            if (userState.instantApp && ps.isUpdateAvailable()) {
13190                return null;
13191            }
13192            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13193                    userState, userId);
13194            if (pi == null) {
13195                return null;
13196            }
13197            final ResolveInfo res = new ResolveInfo();
13198            res.providerInfo = pi;
13199            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13200                res.filter = filter;
13201            }
13202            res.priority = info.getPriority();
13203            res.preferredOrder = provider.owner.mPreferredOrder;
13204            res.match = match;
13205            res.isDefault = info.hasDefault;
13206            res.labelRes = info.labelRes;
13207            res.nonLocalizedLabel = info.nonLocalizedLabel;
13208            res.icon = info.icon;
13209            res.system = res.providerInfo.applicationInfo.isSystemApp();
13210            return res;
13211        }
13212
13213        @Override
13214        protected void sortResults(List<ResolveInfo> results) {
13215            Collections.sort(results, mResolvePrioritySorter);
13216        }
13217
13218        @Override
13219        protected void dumpFilter(PrintWriter out, String prefix,
13220                PackageParser.ProviderIntentInfo filter) {
13221            out.print(prefix);
13222            out.print(
13223                    Integer.toHexString(System.identityHashCode(filter.provider)));
13224            out.print(' ');
13225            filter.provider.printComponentShortName(out);
13226            out.print(" filter ");
13227            out.println(Integer.toHexString(System.identityHashCode(filter)));
13228        }
13229
13230        @Override
13231        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13232            return filter.provider;
13233        }
13234
13235        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13236            PackageParser.Provider provider = (PackageParser.Provider)label;
13237            out.print(prefix); out.print(
13238                    Integer.toHexString(System.identityHashCode(provider)));
13239                    out.print(' ');
13240                    provider.printComponentShortName(out);
13241            if (count > 1) {
13242                out.print(" ("); out.print(count); out.print(" filters)");
13243            }
13244            out.println();
13245        }
13246
13247        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13248                = new ArrayMap<ComponentName, PackageParser.Provider>();
13249        private int mFlags;
13250    }
13251
13252    static final class InstantAppIntentResolver
13253            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13254            AuxiliaryResolveInfo.AuxiliaryFilter> {
13255        /**
13256         * The result that has the highest defined order. Ordering applies on a
13257         * per-package basis. Mapping is from package name to Pair of order and
13258         * EphemeralResolveInfo.
13259         * <p>
13260         * NOTE: This is implemented as a field variable for convenience and efficiency.
13261         * By having a field variable, we're able to track filter ordering as soon as
13262         * a non-zero order is defined. Otherwise, multiple loops across the result set
13263         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13264         * this needs to be contained entirely within {@link #filterResults}.
13265         */
13266        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13267
13268        @Override
13269        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13270            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13271        }
13272
13273        @Override
13274        protected boolean isPackageForFilter(String packageName,
13275                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13276            return true;
13277        }
13278
13279        @Override
13280        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13281                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13282            if (!sUserManager.exists(userId)) {
13283                return null;
13284            }
13285            final String packageName = responseObj.resolveInfo.getPackageName();
13286            final Integer order = responseObj.getOrder();
13287            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13288                    mOrderResult.get(packageName);
13289            // ordering is enabled and this item's order isn't high enough
13290            if (lastOrderResult != null && lastOrderResult.first >= order) {
13291                return null;
13292            }
13293            final InstantAppResolveInfo res = responseObj.resolveInfo;
13294            if (order > 0) {
13295                // non-zero order, enable ordering
13296                mOrderResult.put(packageName, new Pair<>(order, res));
13297            }
13298            return responseObj;
13299        }
13300
13301        @Override
13302        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13303            // only do work if ordering is enabled [most of the time it won't be]
13304            if (mOrderResult.size() == 0) {
13305                return;
13306            }
13307            int resultSize = results.size();
13308            for (int i = 0; i < resultSize; i++) {
13309                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13310                final String packageName = info.getPackageName();
13311                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13312                if (savedInfo == null) {
13313                    // package doesn't having ordering
13314                    continue;
13315                }
13316                if (savedInfo.second == info) {
13317                    // circled back to the highest ordered item; remove from order list
13318                    mOrderResult.remove(packageName);
13319                    if (mOrderResult.size() == 0) {
13320                        // no more ordered items
13321                        break;
13322                    }
13323                    continue;
13324                }
13325                // item has a worse order, remove it from the result list
13326                results.remove(i);
13327                resultSize--;
13328                i--;
13329            }
13330        }
13331    }
13332
13333    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13334            new Comparator<ResolveInfo>() {
13335        public int compare(ResolveInfo r1, ResolveInfo r2) {
13336            int v1 = r1.priority;
13337            int v2 = r2.priority;
13338            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13339            if (v1 != v2) {
13340                return (v1 > v2) ? -1 : 1;
13341            }
13342            v1 = r1.preferredOrder;
13343            v2 = r2.preferredOrder;
13344            if (v1 != v2) {
13345                return (v1 > v2) ? -1 : 1;
13346            }
13347            if (r1.isDefault != r2.isDefault) {
13348                return r1.isDefault ? -1 : 1;
13349            }
13350            v1 = r1.match;
13351            v2 = r2.match;
13352            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13353            if (v1 != v2) {
13354                return (v1 > v2) ? -1 : 1;
13355            }
13356            if (r1.system != r2.system) {
13357                return r1.system ? -1 : 1;
13358            }
13359            if (r1.activityInfo != null) {
13360                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13361            }
13362            if (r1.serviceInfo != null) {
13363                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13364            }
13365            if (r1.providerInfo != null) {
13366                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13367            }
13368            return 0;
13369        }
13370    };
13371
13372    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13373            new Comparator<ProviderInfo>() {
13374        public int compare(ProviderInfo p1, ProviderInfo p2) {
13375            final int v1 = p1.initOrder;
13376            final int v2 = p2.initOrder;
13377            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13378        }
13379    };
13380
13381    @Override
13382    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13383            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13384            final int[] userIds, int[] instantUserIds) {
13385        mHandler.post(new Runnable() {
13386            @Override
13387            public void run() {
13388                try {
13389                    final IActivityManager am = ActivityManager.getService();
13390                    if (am == null) return;
13391                    final int[] resolvedUserIds;
13392                    if (userIds == null) {
13393                        resolvedUserIds = am.getRunningUserIds();
13394                    } else {
13395                        resolvedUserIds = userIds;
13396                    }
13397                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13398                            resolvedUserIds, false);
13399                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13400                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13401                                instantUserIds, true);
13402                    }
13403                } catch (RemoteException ex) {
13404                }
13405            }
13406        });
13407    }
13408
13409    @Override
13410    public void notifyPackageAdded(String packageName) {
13411        final PackageListObserver[] observers;
13412        synchronized (mPackages) {
13413            if (mPackageListObservers.size() == 0) {
13414                return;
13415            }
13416            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13417        }
13418        for (int i = observers.length - 1; i >= 0; --i) {
13419            observers[i].onPackageAdded(packageName);
13420        }
13421    }
13422
13423    @Override
13424    public void notifyPackageRemoved(String packageName) {
13425        final PackageListObserver[] observers;
13426        synchronized (mPackages) {
13427            if (mPackageListObservers.size() == 0) {
13428                return;
13429            }
13430            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13431        }
13432        for (int i = observers.length - 1; i >= 0; --i) {
13433            observers[i].onPackageRemoved(packageName);
13434        }
13435    }
13436
13437    /**
13438     * Sends a broadcast for the given action.
13439     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13440     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13441     * the system and applications allowed to see instant applications to receive package
13442     * lifecycle events for instant applications.
13443     */
13444    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13445            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13446            int[] userIds, boolean isInstantApp)
13447                    throws RemoteException {
13448        for (int id : userIds) {
13449            final Intent intent = new Intent(action,
13450                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13451            final String[] requiredPermissions =
13452                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13453            if (extras != null) {
13454                intent.putExtras(extras);
13455            }
13456            if (targetPkg != null) {
13457                intent.setPackage(targetPkg);
13458            }
13459            // Modify the UID when posting to other users
13460            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13461            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13462                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13463                intent.putExtra(Intent.EXTRA_UID, uid);
13464            }
13465            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13466            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13467            if (DEBUG_BROADCASTS) {
13468                RuntimeException here = new RuntimeException("here");
13469                here.fillInStackTrace();
13470                Slog.d(TAG, "Sending to user " + id + ": "
13471                        + intent.toShortString(false, true, false, false)
13472                        + " " + intent.getExtras(), here);
13473            }
13474            am.broadcastIntent(null, intent, null, finishedReceiver,
13475                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13476                    null, finishedReceiver != null, false, id);
13477        }
13478    }
13479
13480    /**
13481     * Check if the external storage media is available. This is true if there
13482     * is a mounted external storage medium or if the external storage is
13483     * emulated.
13484     */
13485    private boolean isExternalMediaAvailable() {
13486        return mMediaMounted || Environment.isExternalStorageEmulated();
13487    }
13488
13489    @Override
13490    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13491        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13492            return null;
13493        }
13494        if (!isExternalMediaAvailable()) {
13495                // If the external storage is no longer mounted at this point,
13496                // the caller may not have been able to delete all of this
13497                // packages files and can not delete any more.  Bail.
13498            return null;
13499        }
13500        synchronized (mPackages) {
13501            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13502            if (lastPackage != null) {
13503                pkgs.remove(lastPackage);
13504            }
13505            if (pkgs.size() > 0) {
13506                return pkgs.get(0);
13507            }
13508        }
13509        return null;
13510    }
13511
13512    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13513        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13514                userId, andCode ? 1 : 0, packageName);
13515        if (mSystemReady) {
13516            msg.sendToTarget();
13517        } else {
13518            if (mPostSystemReadyMessages == null) {
13519                mPostSystemReadyMessages = new ArrayList<>();
13520            }
13521            mPostSystemReadyMessages.add(msg);
13522        }
13523    }
13524
13525    void startCleaningPackages() {
13526        // reader
13527        if (!isExternalMediaAvailable()) {
13528            return;
13529        }
13530        synchronized (mPackages) {
13531            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13532                return;
13533            }
13534        }
13535        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13536        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13537        IActivityManager am = ActivityManager.getService();
13538        if (am != null) {
13539            int dcsUid = -1;
13540            synchronized (mPackages) {
13541                if (!mDefaultContainerWhitelisted) {
13542                    mDefaultContainerWhitelisted = true;
13543                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13544                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13545                }
13546            }
13547            try {
13548                if (dcsUid > 0) {
13549                    am.backgroundWhitelistUid(dcsUid);
13550                }
13551                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13552                        UserHandle.USER_SYSTEM);
13553            } catch (RemoteException e) {
13554            }
13555        }
13556    }
13557
13558    /**
13559     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13560     * it is acting on behalf on an enterprise or the user).
13561     *
13562     * Note that the ordering of the conditionals in this method is important. The checks we perform
13563     * are as follows, in this order:
13564     *
13565     * 1) If the install is being performed by a system app, we can trust the app to have set the
13566     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13567     *    what it is.
13568     * 2) If the install is being performed by a device or profile owner app, the install reason
13569     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13570     *    set the install reason correctly. If the app targets an older SDK version where install
13571     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13572     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13573     * 3) In all other cases, the install is being performed by a regular app that is neither part
13574     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13575     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13576     *    set to enterprise policy and if so, change it to unknown instead.
13577     */
13578    private int fixUpInstallReason(String installerPackageName, int installerUid,
13579            int installReason) {
13580        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13581                == PERMISSION_GRANTED) {
13582            // If the install is being performed by a system app, we trust that app to have set the
13583            // install reason correctly.
13584            return installReason;
13585        }
13586
13587        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13588            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13589        if (dpm != null) {
13590            ComponentName owner = null;
13591            try {
13592                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13593                if (owner == null) {
13594                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13595                }
13596            } catch (RemoteException e) {
13597            }
13598            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13599                // If the install is being performed by a device or profile owner, the install
13600                // reason should be enterprise policy.
13601                return PackageManager.INSTALL_REASON_POLICY;
13602            }
13603        }
13604
13605        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13606            // If the install is being performed by a regular app (i.e. neither system app nor
13607            // device or profile owner), we have no reason to believe that the app is acting on
13608            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13609            // change it to unknown instead.
13610            return PackageManager.INSTALL_REASON_UNKNOWN;
13611        }
13612
13613        // If the install is being performed by a regular app and the install reason was set to any
13614        // value but enterprise policy, leave the install reason unchanged.
13615        return installReason;
13616    }
13617
13618    void installStage(String packageName, File stagedDir,
13619            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13620            String installerPackageName, int installerUid, UserHandle user,
13621            PackageParser.SigningDetails signingDetails) {
13622        if (DEBUG_INSTANT) {
13623            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13624                Slog.d(TAG, "Ephemeral install of " + packageName);
13625            }
13626        }
13627        final VerificationInfo verificationInfo = new VerificationInfo(
13628                sessionParams.originatingUri, sessionParams.referrerUri,
13629                sessionParams.originatingUid, installerUid);
13630
13631        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13632
13633        final Message msg = mHandler.obtainMessage(INIT_COPY);
13634        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13635                sessionParams.installReason);
13636        final InstallParams params = new InstallParams(origin, null, observer,
13637                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13638                verificationInfo, user, sessionParams.abiOverride,
13639                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13640        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13641        msg.obj = params;
13642
13643        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13644                System.identityHashCode(msg.obj));
13645        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13646                System.identityHashCode(msg.obj));
13647
13648        mHandler.sendMessage(msg);
13649    }
13650
13651    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13652            int userId) {
13653        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13654        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13655        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13656        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13657        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13658                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13659
13660        // Send a session commit broadcast
13661        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13662        info.installReason = pkgSetting.getInstallReason(userId);
13663        info.appPackageName = packageName;
13664        sendSessionCommitBroadcast(info, userId);
13665    }
13666
13667    @Override
13668    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13669            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13670        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13671            return;
13672        }
13673        Bundle extras = new Bundle(1);
13674        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13675        final int uid = UserHandle.getUid(
13676                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13677        extras.putInt(Intent.EXTRA_UID, uid);
13678
13679        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13680                packageName, extras, 0, null, null, userIds, instantUserIds);
13681        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13682            mHandler.post(() -> {
13683                        for (int userId : userIds) {
13684                            sendBootCompletedBroadcastToSystemApp(
13685                                    packageName, includeStopped, userId);
13686                        }
13687                    }
13688            );
13689        }
13690    }
13691
13692    /**
13693     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13694     * automatically without needing an explicit launch.
13695     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13696     */
13697    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13698            int userId) {
13699        // If user is not running, the app didn't miss any broadcast
13700        if (!mUserManagerInternal.isUserRunning(userId)) {
13701            return;
13702        }
13703        final IActivityManager am = ActivityManager.getService();
13704        try {
13705            // Deliver LOCKED_BOOT_COMPLETED first
13706            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13707                    .setPackage(packageName);
13708            if (includeStopped) {
13709                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13710            }
13711            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13712            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13713                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13714
13715            // Deliver BOOT_COMPLETED only if user is unlocked
13716            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13717                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13718                if (includeStopped) {
13719                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13720                }
13721                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13722                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13723            }
13724        } catch (RemoteException e) {
13725            throw e.rethrowFromSystemServer();
13726        }
13727    }
13728
13729    @Override
13730    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13731            int userId) {
13732        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13733        PackageSetting pkgSetting;
13734        final int callingUid = Binder.getCallingUid();
13735        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13736                true /* requireFullPermission */, true /* checkShell */,
13737                "setApplicationHiddenSetting for user " + userId);
13738
13739        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13740            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13741            return false;
13742        }
13743
13744        long callingId = Binder.clearCallingIdentity();
13745        try {
13746            boolean sendAdded = false;
13747            boolean sendRemoved = false;
13748            // writer
13749            synchronized (mPackages) {
13750                pkgSetting = mSettings.mPackages.get(packageName);
13751                if (pkgSetting == null) {
13752                    return false;
13753                }
13754                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13755                    return false;
13756                }
13757                // Do not allow "android" is being disabled
13758                if ("android".equals(packageName)) {
13759                    Slog.w(TAG, "Cannot hide package: android");
13760                    return false;
13761                }
13762                // Cannot hide static shared libs as they are considered
13763                // a part of the using app (emulating static linking). Also
13764                // static libs are installed always on internal storage.
13765                PackageParser.Package pkg = mPackages.get(packageName);
13766                if (pkg != null && pkg.staticSharedLibName != null) {
13767                    Slog.w(TAG, "Cannot hide package: " + packageName
13768                            + " providing static shared library: "
13769                            + pkg.staticSharedLibName);
13770                    return false;
13771                }
13772                // Only allow protected packages to hide themselves.
13773                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13774                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13775                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13776                    return false;
13777                }
13778
13779                if (pkgSetting.getHidden(userId) != hidden) {
13780                    pkgSetting.setHidden(hidden, userId);
13781                    mSettings.writePackageRestrictionsLPr(userId);
13782                    if (hidden) {
13783                        sendRemoved = true;
13784                    } else {
13785                        sendAdded = true;
13786                    }
13787                }
13788            }
13789            if (sendAdded) {
13790                sendPackageAddedForUser(packageName, pkgSetting, userId);
13791                return true;
13792            }
13793            if (sendRemoved) {
13794                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13795                        "hiding pkg");
13796                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13797                return true;
13798            }
13799        } finally {
13800            Binder.restoreCallingIdentity(callingId);
13801        }
13802        return false;
13803    }
13804
13805    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13806            int userId) {
13807        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13808        info.removedPackage = packageName;
13809        info.installerPackageName = pkgSetting.installerPackageName;
13810        info.removedUsers = new int[] {userId};
13811        info.broadcastUsers = new int[] {userId};
13812        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13813        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13814    }
13815
13816    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13817        if (pkgList.length > 0) {
13818            Bundle extras = new Bundle(1);
13819            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13820
13821            sendPackageBroadcast(
13822                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13823                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13824                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13825                    new int[] {userId}, null);
13826        }
13827    }
13828
13829    /**
13830     * Returns true if application is not found or there was an error. Otherwise it returns
13831     * the hidden state of the package for the given user.
13832     */
13833    @Override
13834    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13835        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13836        final int callingUid = Binder.getCallingUid();
13837        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13838                true /* requireFullPermission */, false /* checkShell */,
13839                "getApplicationHidden for user " + userId);
13840        PackageSetting ps;
13841        long callingId = Binder.clearCallingIdentity();
13842        try {
13843            // writer
13844            synchronized (mPackages) {
13845                ps = mSettings.mPackages.get(packageName);
13846                if (ps == null) {
13847                    return true;
13848                }
13849                if (filterAppAccessLPr(ps, callingUid, userId)) {
13850                    return true;
13851                }
13852                return ps.getHidden(userId);
13853            }
13854        } finally {
13855            Binder.restoreCallingIdentity(callingId);
13856        }
13857    }
13858
13859    /**
13860     * @hide
13861     */
13862    @Override
13863    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13864            int installReason) {
13865        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13866                null);
13867        PackageSetting pkgSetting;
13868        final int callingUid = Binder.getCallingUid();
13869        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13870                true /* requireFullPermission */, true /* checkShell */,
13871                "installExistingPackage for user " + userId);
13872        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13873            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13874        }
13875
13876        long callingId = Binder.clearCallingIdentity();
13877        try {
13878            boolean installed = false;
13879            final boolean instantApp =
13880                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13881            final boolean fullApp =
13882                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13883
13884            // writer
13885            synchronized (mPackages) {
13886                pkgSetting = mSettings.mPackages.get(packageName);
13887                if (pkgSetting == null) {
13888                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13889                }
13890                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13891                    // only allow the existing package to be used if it's installed as a full
13892                    // application for at least one user
13893                    boolean installAllowed = false;
13894                    for (int checkUserId : sUserManager.getUserIds()) {
13895                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13896                        if (installAllowed) {
13897                            break;
13898                        }
13899                    }
13900                    if (!installAllowed) {
13901                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13902                    }
13903                }
13904                if (!pkgSetting.getInstalled(userId)) {
13905                    pkgSetting.setInstalled(true, userId);
13906                    pkgSetting.setHidden(false, userId);
13907                    pkgSetting.setInstallReason(installReason, userId);
13908                    mSettings.writePackageRestrictionsLPr(userId);
13909                    mSettings.writeKernelMappingLPr(pkgSetting);
13910                    installed = true;
13911                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13912                    // upgrade app from instant to full; we don't allow app downgrade
13913                    installed = true;
13914                }
13915                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13916            }
13917
13918            if (installed) {
13919                if (pkgSetting.pkg != null) {
13920                    synchronized (mInstallLock) {
13921                        // We don't need to freeze for a brand new install
13922                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13923                    }
13924                }
13925                sendPackageAddedForUser(packageName, pkgSetting, userId);
13926                synchronized (mPackages) {
13927                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13928                }
13929            }
13930        } finally {
13931            Binder.restoreCallingIdentity(callingId);
13932        }
13933
13934        return PackageManager.INSTALL_SUCCEEDED;
13935    }
13936
13937    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13938            boolean instantApp, boolean fullApp) {
13939        // no state specified; do nothing
13940        if (!instantApp && !fullApp) {
13941            return;
13942        }
13943        if (userId != UserHandle.USER_ALL) {
13944            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13945                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13946            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13947                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13948            }
13949        } else {
13950            for (int currentUserId : sUserManager.getUserIds()) {
13951                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13952                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13953                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13954                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13955                }
13956            }
13957        }
13958    }
13959
13960    boolean isUserRestricted(int userId, String restrictionKey) {
13961        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13962        if (restrictions.getBoolean(restrictionKey, false)) {
13963            Log.w(TAG, "User is restricted: " + restrictionKey);
13964            return true;
13965        }
13966        return false;
13967    }
13968
13969    @Override
13970    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13971            int userId) {
13972        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13973        final int callingUid = Binder.getCallingUid();
13974        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13975                true /* requireFullPermission */, true /* checkShell */,
13976                "setPackagesSuspended for user " + userId);
13977
13978        if (ArrayUtils.isEmpty(packageNames)) {
13979            return packageNames;
13980        }
13981
13982        // List of package names for whom the suspended state has changed.
13983        List<String> changedPackages = new ArrayList<>(packageNames.length);
13984        // List of package names for whom the suspended state is not set as requested in this
13985        // method.
13986        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13987        long callingId = Binder.clearCallingIdentity();
13988        try {
13989            for (int i = 0; i < packageNames.length; i++) {
13990                String packageName = packageNames[i];
13991                boolean changed = false;
13992                final int appId;
13993                synchronized (mPackages) {
13994                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13995                    if (pkgSetting == null
13996                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13997                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13998                                + "\". Skipping suspending/un-suspending.");
13999                        unactionedPackages.add(packageName);
14000                        continue;
14001                    }
14002                    appId = pkgSetting.appId;
14003                    if (pkgSetting.getSuspended(userId) != suspended) {
14004                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14005                            unactionedPackages.add(packageName);
14006                            continue;
14007                        }
14008                        pkgSetting.setSuspended(suspended, userId);
14009                        mSettings.writePackageRestrictionsLPr(userId);
14010                        changed = true;
14011                        changedPackages.add(packageName);
14012                    }
14013                }
14014
14015                if (changed && suspended) {
14016                    killApplication(packageName, UserHandle.getUid(userId, appId),
14017                            "suspending package");
14018                }
14019            }
14020        } finally {
14021            Binder.restoreCallingIdentity(callingId);
14022        }
14023
14024        if (!changedPackages.isEmpty()) {
14025            sendPackagesSuspendedForUser(changedPackages.toArray(
14026                    new String[changedPackages.size()]), userId, suspended);
14027        }
14028
14029        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14030    }
14031
14032    @Override
14033    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14034        final int callingUid = Binder.getCallingUid();
14035        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14036                true /* requireFullPermission */, false /* checkShell */,
14037                "isPackageSuspendedForUser for user " + userId);
14038        synchronized (mPackages) {
14039            final PackageSetting ps = mSettings.mPackages.get(packageName);
14040            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14041                throw new IllegalArgumentException("Unknown target package: " + packageName);
14042            }
14043            return ps.getSuspended(userId);
14044        }
14045    }
14046
14047    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14048        if (isPackageDeviceAdmin(packageName, userId)) {
14049            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14050                    + "\": has an active device admin");
14051            return false;
14052        }
14053
14054        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14055        if (packageName.equals(activeLauncherPackageName)) {
14056            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14057                    + "\": contains the active launcher");
14058            return false;
14059        }
14060
14061        if (packageName.equals(mRequiredInstallerPackage)) {
14062            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14063                    + "\": required for package installation");
14064            return false;
14065        }
14066
14067        if (packageName.equals(mRequiredUninstallerPackage)) {
14068            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14069                    + "\": required for package uninstallation");
14070            return false;
14071        }
14072
14073        if (packageName.equals(mRequiredVerifierPackage)) {
14074            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14075                    + "\": required for package verification");
14076            return false;
14077        }
14078
14079        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14080            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14081                    + "\": is the default dialer");
14082            return false;
14083        }
14084
14085        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14086            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14087                    + "\": protected package");
14088            return false;
14089        }
14090
14091        // Cannot suspend static shared libs as they are considered
14092        // a part of the using app (emulating static linking). Also
14093        // static libs are installed always on internal storage.
14094        PackageParser.Package pkg = mPackages.get(packageName);
14095        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14096            Slog.w(TAG, "Cannot suspend package: " + packageName
14097                    + " providing static shared library: "
14098                    + pkg.staticSharedLibName);
14099            return false;
14100        }
14101
14102        return true;
14103    }
14104
14105    private String getActiveLauncherPackageName(int userId) {
14106        Intent intent = new Intent(Intent.ACTION_MAIN);
14107        intent.addCategory(Intent.CATEGORY_HOME);
14108        ResolveInfo resolveInfo = resolveIntent(
14109                intent,
14110                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14111                PackageManager.MATCH_DEFAULT_ONLY,
14112                userId);
14113
14114        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14115    }
14116
14117    private String getDefaultDialerPackageName(int userId) {
14118        synchronized (mPackages) {
14119            return mSettings.getDefaultDialerPackageNameLPw(userId);
14120        }
14121    }
14122
14123    @Override
14124    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14125        mContext.enforceCallingOrSelfPermission(
14126                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14127                "Only package verification agents can verify applications");
14128
14129        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14130        final PackageVerificationResponse response = new PackageVerificationResponse(
14131                verificationCode, Binder.getCallingUid());
14132        msg.arg1 = id;
14133        msg.obj = response;
14134        mHandler.sendMessage(msg);
14135    }
14136
14137    @Override
14138    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14139            long millisecondsToDelay) {
14140        mContext.enforceCallingOrSelfPermission(
14141                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14142                "Only package verification agents can extend verification timeouts");
14143
14144        final PackageVerificationState state = mPendingVerification.get(id);
14145        final PackageVerificationResponse response = new PackageVerificationResponse(
14146                verificationCodeAtTimeout, Binder.getCallingUid());
14147
14148        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14149            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14150        }
14151        if (millisecondsToDelay < 0) {
14152            millisecondsToDelay = 0;
14153        }
14154        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14155                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14156            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14157        }
14158
14159        if ((state != null) && !state.timeoutExtended()) {
14160            state.extendTimeout();
14161
14162            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14163            msg.arg1 = id;
14164            msg.obj = response;
14165            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14166        }
14167    }
14168
14169    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14170            int verificationCode, UserHandle user) {
14171        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14172        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14173        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14174        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14175        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14176
14177        mContext.sendBroadcastAsUser(intent, user,
14178                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14179    }
14180
14181    private ComponentName matchComponentForVerifier(String packageName,
14182            List<ResolveInfo> receivers) {
14183        ActivityInfo targetReceiver = null;
14184
14185        final int NR = receivers.size();
14186        for (int i = 0; i < NR; i++) {
14187            final ResolveInfo info = receivers.get(i);
14188            if (info.activityInfo == null) {
14189                continue;
14190            }
14191
14192            if (packageName.equals(info.activityInfo.packageName)) {
14193                targetReceiver = info.activityInfo;
14194                break;
14195            }
14196        }
14197
14198        if (targetReceiver == null) {
14199            return null;
14200        }
14201
14202        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14203    }
14204
14205    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14206            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14207        if (pkgInfo.verifiers.length == 0) {
14208            return null;
14209        }
14210
14211        final int N = pkgInfo.verifiers.length;
14212        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14213        for (int i = 0; i < N; i++) {
14214            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14215
14216            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14217                    receivers);
14218            if (comp == null) {
14219                continue;
14220            }
14221
14222            final int verifierUid = getUidForVerifier(verifierInfo);
14223            if (verifierUid == -1) {
14224                continue;
14225            }
14226
14227            if (DEBUG_VERIFY) {
14228                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14229                        + " with the correct signature");
14230            }
14231            sufficientVerifiers.add(comp);
14232            verificationState.addSufficientVerifier(verifierUid);
14233        }
14234
14235        return sufficientVerifiers;
14236    }
14237
14238    private int getUidForVerifier(VerifierInfo verifierInfo) {
14239        synchronized (mPackages) {
14240            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14241            if (pkg == null) {
14242                return -1;
14243            } else if (pkg.mSigningDetails.signatures.length != 1) {
14244                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14245                        + " has more than one signature; ignoring");
14246                return -1;
14247            }
14248
14249            /*
14250             * If the public key of the package's signature does not match
14251             * our expected public key, then this is a different package and
14252             * we should skip.
14253             */
14254
14255            final byte[] expectedPublicKey;
14256            try {
14257                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14258                final PublicKey publicKey = verifierSig.getPublicKey();
14259                expectedPublicKey = publicKey.getEncoded();
14260            } catch (CertificateException e) {
14261                return -1;
14262            }
14263
14264            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14265
14266            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14267                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14268                        + " does not have the expected public key; ignoring");
14269                return -1;
14270            }
14271
14272            return pkg.applicationInfo.uid;
14273        }
14274    }
14275
14276    @Override
14277    public void finishPackageInstall(int token, boolean didLaunch) {
14278        enforceSystemOrRoot("Only the system is allowed to finish installs");
14279
14280        if (DEBUG_INSTALL) {
14281            Slog.v(TAG, "BM finishing package install for " + token);
14282        }
14283        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14284
14285        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14286        mHandler.sendMessage(msg);
14287    }
14288
14289    /**
14290     * Get the verification agent timeout.  Used for both the APK verifier and the
14291     * intent filter verifier.
14292     *
14293     * @return verification timeout in milliseconds
14294     */
14295    private long getVerificationTimeout() {
14296        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14297                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14298                DEFAULT_VERIFICATION_TIMEOUT);
14299    }
14300
14301    /**
14302     * Get the default verification agent response code.
14303     *
14304     * @return default verification response code
14305     */
14306    private int getDefaultVerificationResponse(UserHandle user) {
14307        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14308            return PackageManager.VERIFICATION_REJECT;
14309        }
14310        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14311                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14312                DEFAULT_VERIFICATION_RESPONSE);
14313    }
14314
14315    /**
14316     * Check whether or not package verification has been enabled.
14317     *
14318     * @return true if verification should be performed
14319     */
14320    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14321        if (!DEFAULT_VERIFY_ENABLE) {
14322            return false;
14323        }
14324
14325        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14326
14327        // Check if installing from ADB
14328        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14329            // Do not run verification in a test harness environment
14330            if (ActivityManager.isRunningInTestHarness()) {
14331                return false;
14332            }
14333            if (ensureVerifyAppsEnabled) {
14334                return true;
14335            }
14336            // Check if the developer does not want package verification for ADB installs
14337            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14338                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14339                return false;
14340            }
14341        } else {
14342            // only when not installed from ADB, skip verification for instant apps when
14343            // the installer and verifier are the same.
14344            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14345                if (mInstantAppInstallerActivity != null
14346                        && mInstantAppInstallerActivity.packageName.equals(
14347                                mRequiredVerifierPackage)) {
14348                    try {
14349                        mContext.getSystemService(AppOpsManager.class)
14350                                .checkPackage(installerUid, mRequiredVerifierPackage);
14351                        if (DEBUG_VERIFY) {
14352                            Slog.i(TAG, "disable verification for instant app");
14353                        }
14354                        return false;
14355                    } catch (SecurityException ignore) { }
14356                }
14357            }
14358        }
14359
14360        if (ensureVerifyAppsEnabled) {
14361            return true;
14362        }
14363
14364        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14365                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14366    }
14367
14368    @Override
14369    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14370            throws RemoteException {
14371        mContext.enforceCallingOrSelfPermission(
14372                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14373                "Only intentfilter verification agents can verify applications");
14374
14375        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14376        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14377                Binder.getCallingUid(), verificationCode, failedDomains);
14378        msg.arg1 = id;
14379        msg.obj = response;
14380        mHandler.sendMessage(msg);
14381    }
14382
14383    @Override
14384    public int getIntentVerificationStatus(String packageName, int userId) {
14385        final int callingUid = Binder.getCallingUid();
14386        if (UserHandle.getUserId(callingUid) != userId) {
14387            mContext.enforceCallingOrSelfPermission(
14388                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14389                    "getIntentVerificationStatus" + userId);
14390        }
14391        if (getInstantAppPackageName(callingUid) != null) {
14392            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14393        }
14394        synchronized (mPackages) {
14395            final PackageSetting ps = mSettings.mPackages.get(packageName);
14396            if (ps == null
14397                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14398                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14399            }
14400            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14401        }
14402    }
14403
14404    @Override
14405    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14406        mContext.enforceCallingOrSelfPermission(
14407                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14408
14409        boolean result = false;
14410        synchronized (mPackages) {
14411            final PackageSetting ps = mSettings.mPackages.get(packageName);
14412            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14413                return false;
14414            }
14415            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14416        }
14417        if (result) {
14418            scheduleWritePackageRestrictionsLocked(userId);
14419        }
14420        return result;
14421    }
14422
14423    @Override
14424    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14425            String packageName) {
14426        final int callingUid = Binder.getCallingUid();
14427        if (getInstantAppPackageName(callingUid) != null) {
14428            return ParceledListSlice.emptyList();
14429        }
14430        synchronized (mPackages) {
14431            final PackageSetting ps = mSettings.mPackages.get(packageName);
14432            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14433                return ParceledListSlice.emptyList();
14434            }
14435            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14436        }
14437    }
14438
14439    @Override
14440    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14441        if (TextUtils.isEmpty(packageName)) {
14442            return ParceledListSlice.emptyList();
14443        }
14444        final int callingUid = Binder.getCallingUid();
14445        final int callingUserId = UserHandle.getUserId(callingUid);
14446        synchronized (mPackages) {
14447            PackageParser.Package pkg = mPackages.get(packageName);
14448            if (pkg == null || pkg.activities == null) {
14449                return ParceledListSlice.emptyList();
14450            }
14451            if (pkg.mExtras == null) {
14452                return ParceledListSlice.emptyList();
14453            }
14454            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14455            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14456                return ParceledListSlice.emptyList();
14457            }
14458            final int count = pkg.activities.size();
14459            ArrayList<IntentFilter> result = new ArrayList<>();
14460            for (int n=0; n<count; n++) {
14461                PackageParser.Activity activity = pkg.activities.get(n);
14462                if (activity.intents != null && activity.intents.size() > 0) {
14463                    result.addAll(activity.intents);
14464                }
14465            }
14466            return new ParceledListSlice<>(result);
14467        }
14468    }
14469
14470    @Override
14471    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14472        mContext.enforceCallingOrSelfPermission(
14473                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14474        if (UserHandle.getCallingUserId() != userId) {
14475            mContext.enforceCallingOrSelfPermission(
14476                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14477        }
14478
14479        synchronized (mPackages) {
14480            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14481            if (packageName != null) {
14482                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14483                        packageName, userId);
14484            }
14485            return result;
14486        }
14487    }
14488
14489    @Override
14490    public String getDefaultBrowserPackageName(int userId) {
14491        if (UserHandle.getCallingUserId() != userId) {
14492            mContext.enforceCallingOrSelfPermission(
14493                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14494        }
14495        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14496            return null;
14497        }
14498        synchronized (mPackages) {
14499            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14500        }
14501    }
14502
14503    /**
14504     * Get the "allow unknown sources" setting.
14505     *
14506     * @return the current "allow unknown sources" setting
14507     */
14508    private int getUnknownSourcesSettings() {
14509        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14510                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14511                -1);
14512    }
14513
14514    @Override
14515    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14516        final int callingUid = Binder.getCallingUid();
14517        if (getInstantAppPackageName(callingUid) != null) {
14518            return;
14519        }
14520        // writer
14521        synchronized (mPackages) {
14522            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14523            if (targetPackageSetting == null
14524                    || filterAppAccessLPr(
14525                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14526                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14527            }
14528
14529            PackageSetting installerPackageSetting;
14530            if (installerPackageName != null) {
14531                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14532                if (installerPackageSetting == null) {
14533                    throw new IllegalArgumentException("Unknown installer package: "
14534                            + installerPackageName);
14535                }
14536            } else {
14537                installerPackageSetting = null;
14538            }
14539
14540            Signature[] callerSignature;
14541            Object obj = mSettings.getUserIdLPr(callingUid);
14542            if (obj != null) {
14543                if (obj instanceof SharedUserSetting) {
14544                    callerSignature =
14545                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14546                } else if (obj instanceof PackageSetting) {
14547                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14548                } else {
14549                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14550                }
14551            } else {
14552                throw new SecurityException("Unknown calling UID: " + callingUid);
14553            }
14554
14555            // Verify: can't set installerPackageName to a package that is
14556            // not signed with the same cert as the caller.
14557            if (installerPackageSetting != null) {
14558                if (compareSignatures(callerSignature,
14559                        installerPackageSetting.signatures.mSigningDetails.signatures)
14560                        != PackageManager.SIGNATURE_MATCH) {
14561                    throw new SecurityException(
14562                            "Caller does not have same cert as new installer package "
14563                            + installerPackageName);
14564                }
14565            }
14566
14567            // Verify: if target already has an installer package, it must
14568            // be signed with the same cert as the caller.
14569            if (targetPackageSetting.installerPackageName != null) {
14570                PackageSetting setting = mSettings.mPackages.get(
14571                        targetPackageSetting.installerPackageName);
14572                // If the currently set package isn't valid, then it's always
14573                // okay to change it.
14574                if (setting != null) {
14575                    if (compareSignatures(callerSignature,
14576                            setting.signatures.mSigningDetails.signatures)
14577                            != PackageManager.SIGNATURE_MATCH) {
14578                        throw new SecurityException(
14579                                "Caller does not have same cert as old installer package "
14580                                + targetPackageSetting.installerPackageName);
14581                    }
14582                }
14583            }
14584
14585            // Okay!
14586            targetPackageSetting.installerPackageName = installerPackageName;
14587            if (installerPackageName != null) {
14588                mSettings.mInstallerPackages.add(installerPackageName);
14589            }
14590            scheduleWriteSettingsLocked();
14591        }
14592    }
14593
14594    @Override
14595    public void setApplicationCategoryHint(String packageName, int categoryHint,
14596            String callerPackageName) {
14597        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14598            throw new SecurityException("Instant applications don't have access to this method");
14599        }
14600        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14601                callerPackageName);
14602        synchronized (mPackages) {
14603            PackageSetting ps = mSettings.mPackages.get(packageName);
14604            if (ps == null) {
14605                throw new IllegalArgumentException("Unknown target package " + packageName);
14606            }
14607            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14608                throw new IllegalArgumentException("Unknown target package " + packageName);
14609            }
14610            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14611                throw new IllegalArgumentException("Calling package " + callerPackageName
14612                        + " is not installer for " + packageName);
14613            }
14614
14615            if (ps.categoryHint != categoryHint) {
14616                ps.categoryHint = categoryHint;
14617                scheduleWriteSettingsLocked();
14618            }
14619        }
14620    }
14621
14622    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14623        // Queue up an async operation since the package installation may take a little while.
14624        mHandler.post(new Runnable() {
14625            public void run() {
14626                mHandler.removeCallbacks(this);
14627                 // Result object to be returned
14628                PackageInstalledInfo res = new PackageInstalledInfo();
14629                res.setReturnCode(currentStatus);
14630                res.uid = -1;
14631                res.pkg = null;
14632                res.removedInfo = null;
14633                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14634                    args.doPreInstall(res.returnCode);
14635                    synchronized (mInstallLock) {
14636                        installPackageTracedLI(args, res);
14637                    }
14638                    args.doPostInstall(res.returnCode, res.uid);
14639                }
14640
14641                // A restore should be performed at this point if (a) the install
14642                // succeeded, (b) the operation is not an update, and (c) the new
14643                // package has not opted out of backup participation.
14644                final boolean update = res.removedInfo != null
14645                        && res.removedInfo.removedPackage != null;
14646                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14647                boolean doRestore = !update
14648                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14649
14650                // Set up the post-install work request bookkeeping.  This will be used
14651                // and cleaned up by the post-install event handling regardless of whether
14652                // there's a restore pass performed.  Token values are >= 1.
14653                int token;
14654                if (mNextInstallToken < 0) mNextInstallToken = 1;
14655                token = mNextInstallToken++;
14656
14657                PostInstallData data = new PostInstallData(args, res);
14658                mRunningInstalls.put(token, data);
14659                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14660
14661                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14662                    // Pass responsibility to the Backup Manager.  It will perform a
14663                    // restore if appropriate, then pass responsibility back to the
14664                    // Package Manager to run the post-install observer callbacks
14665                    // and broadcasts.
14666                    IBackupManager bm = IBackupManager.Stub.asInterface(
14667                            ServiceManager.getService(Context.BACKUP_SERVICE));
14668                    if (bm != null) {
14669                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14670                                + " to BM for possible restore");
14671                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14672                        try {
14673                            // TODO: http://b/22388012
14674                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14675                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14676                            } else {
14677                                doRestore = false;
14678                            }
14679                        } catch (RemoteException e) {
14680                            // can't happen; the backup manager is local
14681                        } catch (Exception e) {
14682                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14683                            doRestore = false;
14684                        }
14685                    } else {
14686                        Slog.e(TAG, "Backup Manager not found!");
14687                        doRestore = false;
14688                    }
14689                }
14690
14691                if (!doRestore) {
14692                    // No restore possible, or the Backup Manager was mysteriously not
14693                    // available -- just fire the post-install work request directly.
14694                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14695
14696                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14697
14698                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14699                    mHandler.sendMessage(msg);
14700                }
14701            }
14702        });
14703    }
14704
14705    /**
14706     * Callback from PackageSettings whenever an app is first transitioned out of the
14707     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14708     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14709     * here whether the app is the target of an ongoing install, and only send the
14710     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14711     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14712     * handling.
14713     */
14714    void notifyFirstLaunch(final String packageName, final String installerPackage,
14715            final int userId) {
14716        // Serialize this with the rest of the install-process message chain.  In the
14717        // restore-at-install case, this Runnable will necessarily run before the
14718        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14719        // are coherent.  In the non-restore case, the app has already completed install
14720        // and been launched through some other means, so it is not in a problematic
14721        // state for observers to see the FIRST_LAUNCH signal.
14722        mHandler.post(new Runnable() {
14723            @Override
14724            public void run() {
14725                for (int i = 0; i < mRunningInstalls.size(); i++) {
14726                    final PostInstallData data = mRunningInstalls.valueAt(i);
14727                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14728                        continue;
14729                    }
14730                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14731                        // right package; but is it for the right user?
14732                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14733                            if (userId == data.res.newUsers[uIndex]) {
14734                                if (DEBUG_BACKUP) {
14735                                    Slog.i(TAG, "Package " + packageName
14736                                            + " being restored so deferring FIRST_LAUNCH");
14737                                }
14738                                return;
14739                            }
14740                        }
14741                    }
14742                }
14743                // didn't find it, so not being restored
14744                if (DEBUG_BACKUP) {
14745                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14746                }
14747                final boolean isInstantApp = isInstantApp(packageName, userId);
14748                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14749                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14750                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14751            }
14752        });
14753    }
14754
14755    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14756            int[] userIds, int[] instantUserIds) {
14757        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14758                installerPkg, null, userIds, instantUserIds);
14759    }
14760
14761    private abstract class HandlerParams {
14762        private static final int MAX_RETRIES = 4;
14763
14764        /**
14765         * Number of times startCopy() has been attempted and had a non-fatal
14766         * error.
14767         */
14768        private int mRetries = 0;
14769
14770        /** User handle for the user requesting the information or installation. */
14771        private final UserHandle mUser;
14772        String traceMethod;
14773        int traceCookie;
14774
14775        HandlerParams(UserHandle user) {
14776            mUser = user;
14777        }
14778
14779        UserHandle getUser() {
14780            return mUser;
14781        }
14782
14783        HandlerParams setTraceMethod(String traceMethod) {
14784            this.traceMethod = traceMethod;
14785            return this;
14786        }
14787
14788        HandlerParams setTraceCookie(int traceCookie) {
14789            this.traceCookie = traceCookie;
14790            return this;
14791        }
14792
14793        final boolean startCopy() {
14794            boolean res;
14795            try {
14796                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14797
14798                if (++mRetries > MAX_RETRIES) {
14799                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14800                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14801                    handleServiceError();
14802                    return false;
14803                } else {
14804                    handleStartCopy();
14805                    res = true;
14806                }
14807            } catch (RemoteException e) {
14808                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14809                mHandler.sendEmptyMessage(MCS_RECONNECT);
14810                res = false;
14811            }
14812            handleReturnCode();
14813            return res;
14814        }
14815
14816        final void serviceError() {
14817            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14818            handleServiceError();
14819            handleReturnCode();
14820        }
14821
14822        abstract void handleStartCopy() throws RemoteException;
14823        abstract void handleServiceError();
14824        abstract void handleReturnCode();
14825    }
14826
14827    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14828        for (File path : paths) {
14829            try {
14830                mcs.clearDirectory(path.getAbsolutePath());
14831            } catch (RemoteException e) {
14832            }
14833        }
14834    }
14835
14836    static class OriginInfo {
14837        /**
14838         * Location where install is coming from, before it has been
14839         * copied/renamed into place. This could be a single monolithic APK
14840         * file, or a cluster directory. This location may be untrusted.
14841         */
14842        final File file;
14843
14844        /**
14845         * Flag indicating that {@link #file} or {@link #cid} has already been
14846         * staged, meaning downstream users don't need to defensively copy the
14847         * contents.
14848         */
14849        final boolean staged;
14850
14851        /**
14852         * Flag indicating that {@link #file} or {@link #cid} is an already
14853         * installed app that is being moved.
14854         */
14855        final boolean existing;
14856
14857        final String resolvedPath;
14858        final File resolvedFile;
14859
14860        static OriginInfo fromNothing() {
14861            return new OriginInfo(null, false, false);
14862        }
14863
14864        static OriginInfo fromUntrustedFile(File file) {
14865            return new OriginInfo(file, false, false);
14866        }
14867
14868        static OriginInfo fromExistingFile(File file) {
14869            return new OriginInfo(file, false, true);
14870        }
14871
14872        static OriginInfo fromStagedFile(File file) {
14873            return new OriginInfo(file, true, false);
14874        }
14875
14876        private OriginInfo(File file, boolean staged, boolean existing) {
14877            this.file = file;
14878            this.staged = staged;
14879            this.existing = existing;
14880
14881            if (file != null) {
14882                resolvedPath = file.getAbsolutePath();
14883                resolvedFile = file;
14884            } else {
14885                resolvedPath = null;
14886                resolvedFile = null;
14887            }
14888        }
14889    }
14890
14891    static class MoveInfo {
14892        final int moveId;
14893        final String fromUuid;
14894        final String toUuid;
14895        final String packageName;
14896        final String dataAppName;
14897        final int appId;
14898        final String seinfo;
14899        final int targetSdkVersion;
14900
14901        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14902                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14903            this.moveId = moveId;
14904            this.fromUuid = fromUuid;
14905            this.toUuid = toUuid;
14906            this.packageName = packageName;
14907            this.dataAppName = dataAppName;
14908            this.appId = appId;
14909            this.seinfo = seinfo;
14910            this.targetSdkVersion = targetSdkVersion;
14911        }
14912    }
14913
14914    static class VerificationInfo {
14915        /** A constant used to indicate that a uid value is not present. */
14916        public static final int NO_UID = -1;
14917
14918        /** URI referencing where the package was downloaded from. */
14919        final Uri originatingUri;
14920
14921        /** HTTP referrer URI associated with the originatingURI. */
14922        final Uri referrer;
14923
14924        /** UID of the application that the install request originated from. */
14925        final int originatingUid;
14926
14927        /** UID of application requesting the install */
14928        final int installerUid;
14929
14930        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14931            this.originatingUri = originatingUri;
14932            this.referrer = referrer;
14933            this.originatingUid = originatingUid;
14934            this.installerUid = installerUid;
14935        }
14936    }
14937
14938    class InstallParams extends HandlerParams {
14939        final OriginInfo origin;
14940        final MoveInfo move;
14941        final IPackageInstallObserver2 observer;
14942        int installFlags;
14943        final String installerPackageName;
14944        final String volumeUuid;
14945        private InstallArgs mArgs;
14946        private int mRet;
14947        final String packageAbiOverride;
14948        final String[] grantedRuntimePermissions;
14949        final VerificationInfo verificationInfo;
14950        final PackageParser.SigningDetails signingDetails;
14951        final int installReason;
14952
14953        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14954                int installFlags, String installerPackageName, String volumeUuid,
14955                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14956                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14957            super(user);
14958            this.origin = origin;
14959            this.move = move;
14960            this.observer = observer;
14961            this.installFlags = installFlags;
14962            this.installerPackageName = installerPackageName;
14963            this.volumeUuid = volumeUuid;
14964            this.verificationInfo = verificationInfo;
14965            this.packageAbiOverride = packageAbiOverride;
14966            this.grantedRuntimePermissions = grantedPermissions;
14967            this.signingDetails = signingDetails;
14968            this.installReason = installReason;
14969        }
14970
14971        @Override
14972        public String toString() {
14973            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14974                    + " file=" + origin.file + "}";
14975        }
14976
14977        private int installLocationPolicy(PackageInfoLite pkgLite) {
14978            String packageName = pkgLite.packageName;
14979            int installLocation = pkgLite.installLocation;
14980            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14981            // reader
14982            synchronized (mPackages) {
14983                // Currently installed package which the new package is attempting to replace or
14984                // null if no such package is installed.
14985                PackageParser.Package installedPkg = mPackages.get(packageName);
14986                // Package which currently owns the data which the new package will own if installed.
14987                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14988                // will be null whereas dataOwnerPkg will contain information about the package
14989                // which was uninstalled while keeping its data.
14990                PackageParser.Package dataOwnerPkg = installedPkg;
14991                if (dataOwnerPkg  == null) {
14992                    PackageSetting ps = mSettings.mPackages.get(packageName);
14993                    if (ps != null) {
14994                        dataOwnerPkg = ps.pkg;
14995                    }
14996                }
14997
14998                if (dataOwnerPkg != null) {
14999                    // If installed, the package will get access to data left on the device by its
15000                    // predecessor. As a security measure, this is permited only if this is not a
15001                    // version downgrade or if the predecessor package is marked as debuggable and
15002                    // a downgrade is explicitly requested.
15003                    //
15004                    // On debuggable platform builds, downgrades are permitted even for
15005                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15006                    // not offer security guarantees and thus it's OK to disable some security
15007                    // mechanisms to make debugging/testing easier on those builds. However, even on
15008                    // debuggable builds downgrades of packages are permitted only if requested via
15009                    // installFlags. This is because we aim to keep the behavior of debuggable
15010                    // platform builds as close as possible to the behavior of non-debuggable
15011                    // platform builds.
15012                    final boolean downgradeRequested =
15013                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15014                    final boolean packageDebuggable =
15015                                (dataOwnerPkg.applicationInfo.flags
15016                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15017                    final boolean downgradePermitted =
15018                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15019                    if (!downgradePermitted) {
15020                        try {
15021                            checkDowngrade(dataOwnerPkg, pkgLite);
15022                        } catch (PackageManagerException e) {
15023                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15024                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15025                        }
15026                    }
15027                }
15028
15029                if (installedPkg != null) {
15030                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15031                        // Check for updated system application.
15032                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15033                            if (onSd) {
15034                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15035                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15036                            }
15037                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15038                        } else {
15039                            if (onSd) {
15040                                // Install flag overrides everything.
15041                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15042                            }
15043                            // If current upgrade specifies particular preference
15044                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15045                                // Application explicitly specified internal.
15046                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15047                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15048                                // App explictly prefers external. Let policy decide
15049                            } else {
15050                                // Prefer previous location
15051                                if (isExternal(installedPkg)) {
15052                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15053                                }
15054                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15055                            }
15056                        }
15057                    } else {
15058                        // Invalid install. Return error code
15059                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15060                    }
15061                }
15062            }
15063            // All the special cases have been taken care of.
15064            // Return result based on recommended install location.
15065            if (onSd) {
15066                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15067            }
15068            return pkgLite.recommendedInstallLocation;
15069        }
15070
15071        /*
15072         * Invoke remote method to get package information and install
15073         * location values. Override install location based on default
15074         * policy if needed and then create install arguments based
15075         * on the install location.
15076         */
15077        public void handleStartCopy() throws RemoteException {
15078            int ret = PackageManager.INSTALL_SUCCEEDED;
15079
15080            // If we're already staged, we've firmly committed to an install location
15081            if (origin.staged) {
15082                if (origin.file != null) {
15083                    installFlags |= PackageManager.INSTALL_INTERNAL;
15084                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15085                } else {
15086                    throw new IllegalStateException("Invalid stage location");
15087                }
15088            }
15089
15090            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15091            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15092            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15093            PackageInfoLite pkgLite = null;
15094
15095            if (onInt && onSd) {
15096                // Check if both bits are set.
15097                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15098                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15099            } else if (onSd && ephemeral) {
15100                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15101                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15102            } else {
15103                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15104                        packageAbiOverride);
15105
15106                if (DEBUG_INSTANT && ephemeral) {
15107                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15108                }
15109
15110                /*
15111                 * If we have too little free space, try to free cache
15112                 * before giving up.
15113                 */
15114                if (!origin.staged && pkgLite.recommendedInstallLocation
15115                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15116                    // TODO: focus freeing disk space on the target device
15117                    final StorageManager storage = StorageManager.from(mContext);
15118                    final long lowThreshold = storage.getStorageLowBytes(
15119                            Environment.getDataDirectory());
15120
15121                    final long sizeBytes = mContainerService.calculateInstalledSize(
15122                            origin.resolvedPath, packageAbiOverride);
15123
15124                    try {
15125                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15126                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15127                                installFlags, packageAbiOverride);
15128                    } catch (InstallerException e) {
15129                        Slog.w(TAG, "Failed to free cache", e);
15130                    }
15131
15132                    /*
15133                     * The cache free must have deleted the file we
15134                     * downloaded to install.
15135                     *
15136                     * TODO: fix the "freeCache" call to not delete
15137                     *       the file we care about.
15138                     */
15139                    if (pkgLite.recommendedInstallLocation
15140                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15141                        pkgLite.recommendedInstallLocation
15142                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15143                    }
15144                }
15145            }
15146
15147            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15148                int loc = pkgLite.recommendedInstallLocation;
15149                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15150                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15151                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15152                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15153                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15154                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15155                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15156                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15157                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15158                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15159                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15160                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15161                } else {
15162                    // Override with defaults if needed.
15163                    loc = installLocationPolicy(pkgLite);
15164                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15165                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15166                    } else if (!onSd && !onInt) {
15167                        // Override install location with flags
15168                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15169                            // Set the flag to install on external media.
15170                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15171                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15172                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15173                            if (DEBUG_INSTANT) {
15174                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15175                            }
15176                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15177                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15178                                    |PackageManager.INSTALL_INTERNAL);
15179                        } else {
15180                            // Make sure the flag for installing on external
15181                            // media is unset
15182                            installFlags |= PackageManager.INSTALL_INTERNAL;
15183                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15184                        }
15185                    }
15186                }
15187            }
15188
15189            final InstallArgs args = createInstallArgs(this);
15190            mArgs = args;
15191
15192            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15193                // TODO: http://b/22976637
15194                // Apps installed for "all" users use the device owner to verify the app
15195                UserHandle verifierUser = getUser();
15196                if (verifierUser == UserHandle.ALL) {
15197                    verifierUser = UserHandle.SYSTEM;
15198                }
15199
15200                /*
15201                 * Determine if we have any installed package verifiers. If we
15202                 * do, then we'll defer to them to verify the packages.
15203                 */
15204                final int requiredUid = mRequiredVerifierPackage == null ? -1
15205                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15206                                verifierUser.getIdentifier());
15207                final int installerUid =
15208                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15209                if (!origin.existing && requiredUid != -1
15210                        && isVerificationEnabled(
15211                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15212                    final Intent verification = new Intent(
15213                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15214                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15215                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15216                            PACKAGE_MIME_TYPE);
15217                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15218
15219                    // Query all live verifiers based on current user state
15220                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15221                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15222                            false /*allowDynamicSplits*/);
15223
15224                    if (DEBUG_VERIFY) {
15225                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15226                                + verification.toString() + " with " + pkgLite.verifiers.length
15227                                + " optional verifiers");
15228                    }
15229
15230                    final int verificationId = mPendingVerificationToken++;
15231
15232                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15233
15234                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15235                            installerPackageName);
15236
15237                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15238                            installFlags);
15239
15240                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15241                            pkgLite.packageName);
15242
15243                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15244                            pkgLite.versionCode);
15245
15246                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15247                            pkgLite.getLongVersionCode());
15248
15249                    if (verificationInfo != null) {
15250                        if (verificationInfo.originatingUri != null) {
15251                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15252                                    verificationInfo.originatingUri);
15253                        }
15254                        if (verificationInfo.referrer != null) {
15255                            verification.putExtra(Intent.EXTRA_REFERRER,
15256                                    verificationInfo.referrer);
15257                        }
15258                        if (verificationInfo.originatingUid >= 0) {
15259                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15260                                    verificationInfo.originatingUid);
15261                        }
15262                        if (verificationInfo.installerUid >= 0) {
15263                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15264                                    verificationInfo.installerUid);
15265                        }
15266                    }
15267
15268                    final PackageVerificationState verificationState = new PackageVerificationState(
15269                            requiredUid, args);
15270
15271                    mPendingVerification.append(verificationId, verificationState);
15272
15273                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15274                            receivers, verificationState);
15275
15276                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15277                    final long idleDuration = getVerificationTimeout();
15278
15279                    /*
15280                     * If any sufficient verifiers were listed in the package
15281                     * manifest, attempt to ask them.
15282                     */
15283                    if (sufficientVerifiers != null) {
15284                        final int N = sufficientVerifiers.size();
15285                        if (N == 0) {
15286                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15287                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15288                        } else {
15289                            for (int i = 0; i < N; i++) {
15290                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15291                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15292                                        verifierComponent.getPackageName(), idleDuration,
15293                                        verifierUser.getIdentifier(), false, "package verifier");
15294
15295                                final Intent sufficientIntent = new Intent(verification);
15296                                sufficientIntent.setComponent(verifierComponent);
15297                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15298                            }
15299                        }
15300                    }
15301
15302                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15303                            mRequiredVerifierPackage, receivers);
15304                    if (ret == PackageManager.INSTALL_SUCCEEDED
15305                            && mRequiredVerifierPackage != null) {
15306                        Trace.asyncTraceBegin(
15307                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15308                        /*
15309                         * Send the intent to the required verification agent,
15310                         * but only start the verification timeout after the
15311                         * target BroadcastReceivers have run.
15312                         */
15313                        verification.setComponent(requiredVerifierComponent);
15314                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15315                                mRequiredVerifierPackage, idleDuration,
15316                                verifierUser.getIdentifier(), false, "package verifier");
15317                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15318                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15319                                new BroadcastReceiver() {
15320                                    @Override
15321                                    public void onReceive(Context context, Intent intent) {
15322                                        final Message msg = mHandler
15323                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15324                                        msg.arg1 = verificationId;
15325                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15326                                    }
15327                                }, null, 0, null, null);
15328
15329                        /*
15330                         * We don't want the copy to proceed until verification
15331                         * succeeds, so null out this field.
15332                         */
15333                        mArgs = null;
15334                    }
15335                } else {
15336                    /*
15337                     * No package verification is enabled, so immediately start
15338                     * the remote call to initiate copy using temporary file.
15339                     */
15340                    ret = args.copyApk(mContainerService, true);
15341                }
15342            }
15343
15344            mRet = ret;
15345        }
15346
15347        @Override
15348        void handleReturnCode() {
15349            // If mArgs is null, then MCS couldn't be reached. When it
15350            // reconnects, it will try again to install. At that point, this
15351            // will succeed.
15352            if (mArgs != null) {
15353                processPendingInstall(mArgs, mRet);
15354            }
15355        }
15356
15357        @Override
15358        void handleServiceError() {
15359            mArgs = createInstallArgs(this);
15360            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15361        }
15362    }
15363
15364    private InstallArgs createInstallArgs(InstallParams params) {
15365        if (params.move != null) {
15366            return new MoveInstallArgs(params);
15367        } else {
15368            return new FileInstallArgs(params);
15369        }
15370    }
15371
15372    /**
15373     * Create args that describe an existing installed package. Typically used
15374     * when cleaning up old installs, or used as a move source.
15375     */
15376    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15377            String resourcePath, String[] instructionSets) {
15378        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15379    }
15380
15381    static abstract class InstallArgs {
15382        /** @see InstallParams#origin */
15383        final OriginInfo origin;
15384        /** @see InstallParams#move */
15385        final MoveInfo move;
15386
15387        final IPackageInstallObserver2 observer;
15388        // Always refers to PackageManager flags only
15389        final int installFlags;
15390        final String installerPackageName;
15391        final String volumeUuid;
15392        final UserHandle user;
15393        final String abiOverride;
15394        final String[] installGrantPermissions;
15395        /** If non-null, drop an async trace when the install completes */
15396        final String traceMethod;
15397        final int traceCookie;
15398        final PackageParser.SigningDetails signingDetails;
15399        final int installReason;
15400
15401        // The list of instruction sets supported by this app. This is currently
15402        // only used during the rmdex() phase to clean up resources. We can get rid of this
15403        // if we move dex files under the common app path.
15404        /* nullable */ String[] instructionSets;
15405
15406        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15407                int installFlags, String installerPackageName, String volumeUuid,
15408                UserHandle user, String[] instructionSets,
15409                String abiOverride, String[] installGrantPermissions,
15410                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15411                int installReason) {
15412            this.origin = origin;
15413            this.move = move;
15414            this.installFlags = installFlags;
15415            this.observer = observer;
15416            this.installerPackageName = installerPackageName;
15417            this.volumeUuid = volumeUuid;
15418            this.user = user;
15419            this.instructionSets = instructionSets;
15420            this.abiOverride = abiOverride;
15421            this.installGrantPermissions = installGrantPermissions;
15422            this.traceMethod = traceMethod;
15423            this.traceCookie = traceCookie;
15424            this.signingDetails = signingDetails;
15425            this.installReason = installReason;
15426        }
15427
15428        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15429        abstract int doPreInstall(int status);
15430
15431        /**
15432         * Rename package into final resting place. All paths on the given
15433         * scanned package should be updated to reflect the rename.
15434         */
15435        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15436        abstract int doPostInstall(int status, int uid);
15437
15438        /** @see PackageSettingBase#codePathString */
15439        abstract String getCodePath();
15440        /** @see PackageSettingBase#resourcePathString */
15441        abstract String getResourcePath();
15442
15443        // Need installer lock especially for dex file removal.
15444        abstract void cleanUpResourcesLI();
15445        abstract boolean doPostDeleteLI(boolean delete);
15446
15447        /**
15448         * Called before the source arguments are copied. This is used mostly
15449         * for MoveParams when it needs to read the source file to put it in the
15450         * destination.
15451         */
15452        int doPreCopy() {
15453            return PackageManager.INSTALL_SUCCEEDED;
15454        }
15455
15456        /**
15457         * Called after the source arguments are copied. This is used mostly for
15458         * MoveParams when it needs to read the source file to put it in the
15459         * destination.
15460         */
15461        int doPostCopy(int uid) {
15462            return PackageManager.INSTALL_SUCCEEDED;
15463        }
15464
15465        protected boolean isFwdLocked() {
15466            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15467        }
15468
15469        protected boolean isExternalAsec() {
15470            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15471        }
15472
15473        protected boolean isEphemeral() {
15474            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15475        }
15476
15477        UserHandle getUser() {
15478            return user;
15479        }
15480    }
15481
15482    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15483        if (!allCodePaths.isEmpty()) {
15484            if (instructionSets == null) {
15485                throw new IllegalStateException("instructionSet == null");
15486            }
15487            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15488            for (String codePath : allCodePaths) {
15489                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15490                    try {
15491                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15492                    } catch (InstallerException ignored) {
15493                    }
15494                }
15495            }
15496        }
15497    }
15498
15499    /**
15500     * Logic to handle installation of non-ASEC applications, including copying
15501     * and renaming logic.
15502     */
15503    class FileInstallArgs extends InstallArgs {
15504        private File codeFile;
15505        private File resourceFile;
15506
15507        // Example topology:
15508        // /data/app/com.example/base.apk
15509        // /data/app/com.example/split_foo.apk
15510        // /data/app/com.example/lib/arm/libfoo.so
15511        // /data/app/com.example/lib/arm64/libfoo.so
15512        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15513
15514        /** New install */
15515        FileInstallArgs(InstallParams params) {
15516            super(params.origin, params.move, params.observer, params.installFlags,
15517                    params.installerPackageName, params.volumeUuid,
15518                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15519                    params.grantedRuntimePermissions,
15520                    params.traceMethod, params.traceCookie, params.signingDetails,
15521                    params.installReason);
15522            if (isFwdLocked()) {
15523                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15524            }
15525        }
15526
15527        /** Existing install */
15528        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15529            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15530                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15531                    PackageManager.INSTALL_REASON_UNKNOWN);
15532            this.codeFile = (codePath != null) ? new File(codePath) : null;
15533            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15534        }
15535
15536        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15537            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15538            try {
15539                return doCopyApk(imcs, temp);
15540            } finally {
15541                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15542            }
15543        }
15544
15545        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15546            if (origin.staged) {
15547                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15548                codeFile = origin.file;
15549                resourceFile = origin.file;
15550                return PackageManager.INSTALL_SUCCEEDED;
15551            }
15552
15553            try {
15554                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15555                final File tempDir =
15556                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15557                codeFile = tempDir;
15558                resourceFile = tempDir;
15559            } catch (IOException e) {
15560                Slog.w(TAG, "Failed to create copy file: " + e);
15561                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15562            }
15563
15564            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15565                @Override
15566                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15567                    if (!FileUtils.isValidExtFilename(name)) {
15568                        throw new IllegalArgumentException("Invalid filename: " + name);
15569                    }
15570                    try {
15571                        final File file = new File(codeFile, name);
15572                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15573                                O_RDWR | O_CREAT, 0644);
15574                        Os.chmod(file.getAbsolutePath(), 0644);
15575                        return new ParcelFileDescriptor(fd);
15576                    } catch (ErrnoException e) {
15577                        throw new RemoteException("Failed to open: " + e.getMessage());
15578                    }
15579                }
15580            };
15581
15582            int ret = PackageManager.INSTALL_SUCCEEDED;
15583            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15584            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15585                Slog.e(TAG, "Failed to copy package");
15586                return ret;
15587            }
15588
15589            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15590            NativeLibraryHelper.Handle handle = null;
15591            try {
15592                handle = NativeLibraryHelper.Handle.create(codeFile);
15593                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15594                        abiOverride);
15595            } catch (IOException e) {
15596                Slog.e(TAG, "Copying native libraries failed", e);
15597                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15598            } finally {
15599                IoUtils.closeQuietly(handle);
15600            }
15601
15602            return ret;
15603        }
15604
15605        int doPreInstall(int status) {
15606            if (status != PackageManager.INSTALL_SUCCEEDED) {
15607                cleanUp();
15608            }
15609            return status;
15610        }
15611
15612        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15613            if (status != PackageManager.INSTALL_SUCCEEDED) {
15614                cleanUp();
15615                return false;
15616            }
15617
15618            final File targetDir = codeFile.getParentFile();
15619            final File beforeCodeFile = codeFile;
15620            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15621
15622            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15623            try {
15624                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15625            } catch (ErrnoException e) {
15626                Slog.w(TAG, "Failed to rename", e);
15627                return false;
15628            }
15629
15630            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15631                Slog.w(TAG, "Failed to restorecon");
15632                return false;
15633            }
15634
15635            // Reflect the rename internally
15636            codeFile = afterCodeFile;
15637            resourceFile = afterCodeFile;
15638
15639            // Reflect the rename in scanned details
15640            try {
15641                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15642            } catch (IOException e) {
15643                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15644                return false;
15645            }
15646            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15647                    afterCodeFile, pkg.baseCodePath));
15648            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15649                    afterCodeFile, pkg.splitCodePaths));
15650
15651            // Reflect the rename in app info
15652            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15653            pkg.setApplicationInfoCodePath(pkg.codePath);
15654            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15655            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15656            pkg.setApplicationInfoResourcePath(pkg.codePath);
15657            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15658            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15659
15660            return true;
15661        }
15662
15663        int doPostInstall(int status, int uid) {
15664            if (status != PackageManager.INSTALL_SUCCEEDED) {
15665                cleanUp();
15666            }
15667            return status;
15668        }
15669
15670        @Override
15671        String getCodePath() {
15672            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15673        }
15674
15675        @Override
15676        String getResourcePath() {
15677            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15678        }
15679
15680        private boolean cleanUp() {
15681            if (codeFile == null || !codeFile.exists()) {
15682                return false;
15683            }
15684
15685            removeCodePathLI(codeFile);
15686
15687            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15688                resourceFile.delete();
15689            }
15690
15691            return true;
15692        }
15693
15694        void cleanUpResourcesLI() {
15695            // Try enumerating all code paths before deleting
15696            List<String> allCodePaths = Collections.EMPTY_LIST;
15697            if (codeFile != null && codeFile.exists()) {
15698                try {
15699                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15700                    allCodePaths = pkg.getAllCodePaths();
15701                } catch (PackageParserException e) {
15702                    // Ignored; we tried our best
15703                }
15704            }
15705
15706            cleanUp();
15707            removeDexFiles(allCodePaths, instructionSets);
15708        }
15709
15710        boolean doPostDeleteLI(boolean delete) {
15711            // XXX err, shouldn't we respect the delete flag?
15712            cleanUpResourcesLI();
15713            return true;
15714        }
15715    }
15716
15717    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15718            PackageManagerException {
15719        if (copyRet < 0) {
15720            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15721                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15722                throw new PackageManagerException(copyRet, message);
15723            }
15724        }
15725    }
15726
15727    /**
15728     * Extract the StorageManagerService "container ID" from the full code path of an
15729     * .apk.
15730     */
15731    static String cidFromCodePath(String fullCodePath) {
15732        int eidx = fullCodePath.lastIndexOf("/");
15733        String subStr1 = fullCodePath.substring(0, eidx);
15734        int sidx = subStr1.lastIndexOf("/");
15735        return subStr1.substring(sidx+1, eidx);
15736    }
15737
15738    /**
15739     * Logic to handle movement of existing installed applications.
15740     */
15741    class MoveInstallArgs extends InstallArgs {
15742        private File codeFile;
15743        private File resourceFile;
15744
15745        /** New install */
15746        MoveInstallArgs(InstallParams params) {
15747            super(params.origin, params.move, params.observer, params.installFlags,
15748                    params.installerPackageName, params.volumeUuid,
15749                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15750                    params.grantedRuntimePermissions,
15751                    params.traceMethod, params.traceCookie, params.signingDetails,
15752                    params.installReason);
15753        }
15754
15755        int copyApk(IMediaContainerService imcs, boolean temp) {
15756            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15757                    + move.fromUuid + " to " + move.toUuid);
15758            synchronized (mInstaller) {
15759                try {
15760                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15761                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15762                } catch (InstallerException e) {
15763                    Slog.w(TAG, "Failed to move app", e);
15764                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15765                }
15766            }
15767
15768            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15769            resourceFile = codeFile;
15770            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15771
15772            return PackageManager.INSTALL_SUCCEEDED;
15773        }
15774
15775        int doPreInstall(int status) {
15776            if (status != PackageManager.INSTALL_SUCCEEDED) {
15777                cleanUp(move.toUuid);
15778            }
15779            return status;
15780        }
15781
15782        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15783            if (status != PackageManager.INSTALL_SUCCEEDED) {
15784                cleanUp(move.toUuid);
15785                return false;
15786            }
15787
15788            // Reflect the move in app info
15789            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15790            pkg.setApplicationInfoCodePath(pkg.codePath);
15791            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15792            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15793            pkg.setApplicationInfoResourcePath(pkg.codePath);
15794            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15795            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15796
15797            return true;
15798        }
15799
15800        int doPostInstall(int status, int uid) {
15801            if (status == PackageManager.INSTALL_SUCCEEDED) {
15802                cleanUp(move.fromUuid);
15803            } else {
15804                cleanUp(move.toUuid);
15805            }
15806            return status;
15807        }
15808
15809        @Override
15810        String getCodePath() {
15811            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15812        }
15813
15814        @Override
15815        String getResourcePath() {
15816            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15817        }
15818
15819        private boolean cleanUp(String volumeUuid) {
15820            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15821                    move.dataAppName);
15822            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15823            final int[] userIds = sUserManager.getUserIds();
15824            synchronized (mInstallLock) {
15825                // Clean up both app data and code
15826                // All package moves are frozen until finished
15827                for (int userId : userIds) {
15828                    try {
15829                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15830                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15831                    } catch (InstallerException e) {
15832                        Slog.w(TAG, String.valueOf(e));
15833                    }
15834                }
15835                removeCodePathLI(codeFile);
15836            }
15837            return true;
15838        }
15839
15840        void cleanUpResourcesLI() {
15841            throw new UnsupportedOperationException();
15842        }
15843
15844        boolean doPostDeleteLI(boolean delete) {
15845            throw new UnsupportedOperationException();
15846        }
15847    }
15848
15849    static String getAsecPackageName(String packageCid) {
15850        int idx = packageCid.lastIndexOf("-");
15851        if (idx == -1) {
15852            return packageCid;
15853        }
15854        return packageCid.substring(0, idx);
15855    }
15856
15857    // Utility method used to create code paths based on package name and available index.
15858    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15859        String idxStr = "";
15860        int idx = 1;
15861        // Fall back to default value of idx=1 if prefix is not
15862        // part of oldCodePath
15863        if (oldCodePath != null) {
15864            String subStr = oldCodePath;
15865            // Drop the suffix right away
15866            if (suffix != null && subStr.endsWith(suffix)) {
15867                subStr = subStr.substring(0, subStr.length() - suffix.length());
15868            }
15869            // If oldCodePath already contains prefix find out the
15870            // ending index to either increment or decrement.
15871            int sidx = subStr.lastIndexOf(prefix);
15872            if (sidx != -1) {
15873                subStr = subStr.substring(sidx + prefix.length());
15874                if (subStr != null) {
15875                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15876                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15877                    }
15878                    try {
15879                        idx = Integer.parseInt(subStr);
15880                        if (idx <= 1) {
15881                            idx++;
15882                        } else {
15883                            idx--;
15884                        }
15885                    } catch(NumberFormatException e) {
15886                    }
15887                }
15888            }
15889        }
15890        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15891        return prefix + idxStr;
15892    }
15893
15894    private File getNextCodePath(File targetDir, String packageName) {
15895        File result;
15896        SecureRandom random = new SecureRandom();
15897        byte[] bytes = new byte[16];
15898        do {
15899            random.nextBytes(bytes);
15900            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15901            result = new File(targetDir, packageName + "-" + suffix);
15902        } while (result.exists());
15903        return result;
15904    }
15905
15906    // Utility method that returns the relative package path with respect
15907    // to the installation directory. Like say for /data/data/com.test-1.apk
15908    // string com.test-1 is returned.
15909    static String deriveCodePathName(String codePath) {
15910        if (codePath == null) {
15911            return null;
15912        }
15913        final File codeFile = new File(codePath);
15914        final String name = codeFile.getName();
15915        if (codeFile.isDirectory()) {
15916            return name;
15917        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15918            final int lastDot = name.lastIndexOf('.');
15919            return name.substring(0, lastDot);
15920        } else {
15921            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15922            return null;
15923        }
15924    }
15925
15926    static class PackageInstalledInfo {
15927        String name;
15928        int uid;
15929        // The set of users that originally had this package installed.
15930        int[] origUsers;
15931        // The set of users that now have this package installed.
15932        int[] newUsers;
15933        PackageParser.Package pkg;
15934        int returnCode;
15935        String returnMsg;
15936        String installerPackageName;
15937        PackageRemovedInfo removedInfo;
15938        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15939
15940        public void setError(int code, String msg) {
15941            setReturnCode(code);
15942            setReturnMessage(msg);
15943            Slog.w(TAG, msg);
15944        }
15945
15946        public void setError(String msg, PackageParserException e) {
15947            setReturnCode(e.error);
15948            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15949            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15950            for (int i = 0; i < childCount; i++) {
15951                addedChildPackages.valueAt(i).setError(msg, e);
15952            }
15953            Slog.w(TAG, msg, e);
15954        }
15955
15956        public void setError(String msg, PackageManagerException e) {
15957            returnCode = e.error;
15958            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15959            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15960            for (int i = 0; i < childCount; i++) {
15961                addedChildPackages.valueAt(i).setError(msg, e);
15962            }
15963            Slog.w(TAG, msg, e);
15964        }
15965
15966        public void setReturnCode(int returnCode) {
15967            this.returnCode = returnCode;
15968            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15969            for (int i = 0; i < childCount; i++) {
15970                addedChildPackages.valueAt(i).returnCode = returnCode;
15971            }
15972        }
15973
15974        private void setReturnMessage(String returnMsg) {
15975            this.returnMsg = returnMsg;
15976            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15977            for (int i = 0; i < childCount; i++) {
15978                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15979            }
15980        }
15981
15982        // In some error cases we want to convey more info back to the observer
15983        String origPackage;
15984        String origPermission;
15985    }
15986
15987    /*
15988     * Install a non-existing package.
15989     */
15990    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15991            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15992            String volumeUuid, PackageInstalledInfo res, int installReason) {
15993        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15994
15995        // Remember this for later, in case we need to rollback this install
15996        String pkgName = pkg.packageName;
15997
15998        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15999
16000        synchronized(mPackages) {
16001            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16002            if (renamedPackage != null) {
16003                // A package with the same name is already installed, though
16004                // it has been renamed to an older name.  The package we
16005                // are trying to install should be installed as an update to
16006                // the existing one, but that has not been requested, so bail.
16007                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16008                        + " without first uninstalling package running as "
16009                        + renamedPackage);
16010                return;
16011            }
16012            if (mPackages.containsKey(pkgName)) {
16013                // Don't allow installation over an existing package with the same name.
16014                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16015                        + " without first uninstalling.");
16016                return;
16017            }
16018        }
16019
16020        try {
16021            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16022                    System.currentTimeMillis(), user);
16023
16024            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16025
16026            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16027                prepareAppDataAfterInstallLIF(newPackage);
16028
16029            } else {
16030                // Remove package from internal structures, but keep around any
16031                // data that might have already existed
16032                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16033                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16034            }
16035        } catch (PackageManagerException e) {
16036            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16037        }
16038
16039        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16040    }
16041
16042    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16043        try (DigestInputStream digestStream =
16044                new DigestInputStream(new FileInputStream(file), digest)) {
16045            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16046        }
16047    }
16048
16049    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16050            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16051            PackageInstalledInfo res, int installReason) {
16052        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16053
16054        final PackageParser.Package oldPackage;
16055        final PackageSetting ps;
16056        final String pkgName = pkg.packageName;
16057        final int[] allUsers;
16058        final int[] installedUsers;
16059
16060        synchronized(mPackages) {
16061            oldPackage = mPackages.get(pkgName);
16062            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16063
16064            // don't allow upgrade to target a release SDK from a pre-release SDK
16065            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16066                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16067            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16068                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16069            if (oldTargetsPreRelease
16070                    && !newTargetsPreRelease
16071                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16072                Slog.w(TAG, "Can't install package targeting released sdk");
16073                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16074                return;
16075            }
16076
16077            ps = mSettings.mPackages.get(pkgName);
16078
16079            // verify signatures are valid
16080            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16081            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16082                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16083                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16084                            "New package not signed by keys specified by upgrade-keysets: "
16085                                    + pkgName);
16086                    return;
16087                }
16088            } else {
16089
16090                // default to original signature matching
16091                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16092                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16093                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16094                            "New package has a different signature: " + pkgName);
16095                    return;
16096                }
16097            }
16098
16099            // don't allow a system upgrade unless the upgrade hash matches
16100            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16101                byte[] digestBytes = null;
16102                try {
16103                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16104                    updateDigest(digest, new File(pkg.baseCodePath));
16105                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16106                        for (String path : pkg.splitCodePaths) {
16107                            updateDigest(digest, new File(path));
16108                        }
16109                    }
16110                    digestBytes = digest.digest();
16111                } catch (NoSuchAlgorithmException | IOException e) {
16112                    res.setError(INSTALL_FAILED_INVALID_APK,
16113                            "Could not compute hash: " + pkgName);
16114                    return;
16115                }
16116                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16117                    res.setError(INSTALL_FAILED_INVALID_APK,
16118                            "New package fails restrict-update check: " + pkgName);
16119                    return;
16120                }
16121                // retain upgrade restriction
16122                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16123            }
16124
16125            // Check for shared user id changes
16126            String invalidPackageName =
16127                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16128            if (invalidPackageName != null) {
16129                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16130                        "Package " + invalidPackageName + " tried to change user "
16131                                + oldPackage.mSharedUserId);
16132                return;
16133            }
16134
16135            // check if the new package supports all of the abis which the old package supports
16136            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16137            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16138            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16139                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16140                        "Update to package " + pkgName + " doesn't support multi arch");
16141                return;
16142            }
16143
16144            // In case of rollback, remember per-user/profile install state
16145            allUsers = sUserManager.getUserIds();
16146            installedUsers = ps.queryInstalledUsers(allUsers, true);
16147
16148            // don't allow an upgrade from full to ephemeral
16149            if (isInstantApp) {
16150                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16151                    for (int currentUser : allUsers) {
16152                        if (!ps.getInstantApp(currentUser)) {
16153                            // can't downgrade from full to instant
16154                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16155                                    + " for user: " + currentUser);
16156                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16157                            return;
16158                        }
16159                    }
16160                } else if (!ps.getInstantApp(user.getIdentifier())) {
16161                    // can't downgrade from full to instant
16162                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16163                            + " for user: " + user.getIdentifier());
16164                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16165                    return;
16166                }
16167            }
16168        }
16169
16170        // Update what is removed
16171        res.removedInfo = new PackageRemovedInfo(this);
16172        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16173        res.removedInfo.removedPackage = oldPackage.packageName;
16174        res.removedInfo.installerPackageName = ps.installerPackageName;
16175        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16176        res.removedInfo.isUpdate = true;
16177        res.removedInfo.origUsers = installedUsers;
16178        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16179        for (int i = 0; i < installedUsers.length; i++) {
16180            final int userId = installedUsers[i];
16181            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16182        }
16183
16184        final int childCount = (oldPackage.childPackages != null)
16185                ? oldPackage.childPackages.size() : 0;
16186        for (int i = 0; i < childCount; i++) {
16187            boolean childPackageUpdated = false;
16188            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16189            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16190            if (res.addedChildPackages != null) {
16191                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16192                if (childRes != null) {
16193                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16194                    childRes.removedInfo.removedPackage = childPkg.packageName;
16195                    if (childPs != null) {
16196                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16197                    }
16198                    childRes.removedInfo.isUpdate = true;
16199                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16200                    childPackageUpdated = true;
16201                }
16202            }
16203            if (!childPackageUpdated) {
16204                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16205                childRemovedRes.removedPackage = childPkg.packageName;
16206                if (childPs != null) {
16207                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16208                }
16209                childRemovedRes.isUpdate = false;
16210                childRemovedRes.dataRemoved = true;
16211                synchronized (mPackages) {
16212                    if (childPs != null) {
16213                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16214                    }
16215                }
16216                if (res.removedInfo.removedChildPackages == null) {
16217                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16218                }
16219                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16220            }
16221        }
16222
16223        boolean sysPkg = (isSystemApp(oldPackage));
16224        if (sysPkg) {
16225            // Set the system/privileged/oem/vendor/product flags as needed
16226            final boolean privileged =
16227                    (oldPackage.applicationInfo.privateFlags
16228                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16229            final boolean oem =
16230                    (oldPackage.applicationInfo.privateFlags
16231                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16232            final boolean vendor =
16233                    (oldPackage.applicationInfo.privateFlags
16234                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16235            final boolean product =
16236                    (oldPackage.applicationInfo.privateFlags
16237                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16238            final @ParseFlags int systemParseFlags = parseFlags;
16239            final @ScanFlags int systemScanFlags = scanFlags
16240                    | SCAN_AS_SYSTEM
16241                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16242                    | (oem ? SCAN_AS_OEM : 0)
16243                    | (vendor ? SCAN_AS_VENDOR : 0)
16244                    | (product ? SCAN_AS_PRODUCT : 0);
16245
16246            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16247                    user, allUsers, installerPackageName, res, installReason);
16248        } else {
16249            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16250                    user, allUsers, installerPackageName, res, installReason);
16251        }
16252    }
16253
16254    @Override
16255    public List<String> getPreviousCodePaths(String packageName) {
16256        final int callingUid = Binder.getCallingUid();
16257        final List<String> result = new ArrayList<>();
16258        if (getInstantAppPackageName(callingUid) != null) {
16259            return result;
16260        }
16261        final PackageSetting ps = mSettings.mPackages.get(packageName);
16262        if (ps != null
16263                && ps.oldCodePaths != null
16264                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16265            result.addAll(ps.oldCodePaths);
16266        }
16267        return result;
16268    }
16269
16270    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16271            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16272            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16273            String installerPackageName, PackageInstalledInfo res, int installReason) {
16274        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16275                + deletedPackage);
16276
16277        String pkgName = deletedPackage.packageName;
16278        boolean deletedPkg = true;
16279        boolean addedPkg = false;
16280        boolean updatedSettings = false;
16281        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16282        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16283                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16284
16285        final long origUpdateTime = (pkg.mExtras != null)
16286                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16287
16288        // First delete the existing package while retaining the data directory
16289        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16290                res.removedInfo, true, pkg)) {
16291            // If the existing package wasn't successfully deleted
16292            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16293            deletedPkg = false;
16294        } else {
16295            // Successfully deleted the old package; proceed with replace.
16296
16297            // If deleted package lived in a container, give users a chance to
16298            // relinquish resources before killing.
16299            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16300                if (DEBUG_INSTALL) {
16301                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16302                }
16303                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16304                final ArrayList<String> pkgList = new ArrayList<String>(1);
16305                pkgList.add(deletedPackage.applicationInfo.packageName);
16306                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16307            }
16308
16309            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16310                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16311
16312            try {
16313                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16314                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16315                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16316                        installReason);
16317
16318                // Update the in-memory copy of the previous code paths.
16319                PackageSetting ps = mSettings.mPackages.get(pkgName);
16320                if (!killApp) {
16321                    if (ps.oldCodePaths == null) {
16322                        ps.oldCodePaths = new ArraySet<>();
16323                    }
16324                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16325                    if (deletedPackage.splitCodePaths != null) {
16326                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16327                    }
16328                } else {
16329                    ps.oldCodePaths = null;
16330                }
16331                if (ps.childPackageNames != null) {
16332                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16333                        final String childPkgName = ps.childPackageNames.get(i);
16334                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16335                        childPs.oldCodePaths = ps.oldCodePaths;
16336                    }
16337                }
16338                // set instant app status, but, only if it's explicitly specified
16339                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16340                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16341                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16342                prepareAppDataAfterInstallLIF(newPackage);
16343                addedPkg = true;
16344                mDexManager.notifyPackageUpdated(newPackage.packageName,
16345                        newPackage.baseCodePath, newPackage.splitCodePaths);
16346            } catch (PackageManagerException e) {
16347                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16348            }
16349        }
16350
16351        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16352            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16353
16354            // Revert all internal state mutations and added folders for the failed install
16355            if (addedPkg) {
16356                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16357                        res.removedInfo, true, null);
16358            }
16359
16360            // Restore the old package
16361            if (deletedPkg) {
16362                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16363                File restoreFile = new File(deletedPackage.codePath);
16364                // Parse old package
16365                boolean oldExternal = isExternal(deletedPackage);
16366                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16367                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16368                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16369                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16370                try {
16371                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16372                            null);
16373                } catch (PackageManagerException e) {
16374                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16375                            + e.getMessage());
16376                    return;
16377                }
16378
16379                synchronized (mPackages) {
16380                    // Ensure the installer package name up to date
16381                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16382
16383                    // Update permissions for restored package
16384                    mPermissionManager.updatePermissions(
16385                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16386                            mPermissionCallback);
16387
16388                    mSettings.writeLPr();
16389                }
16390
16391                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16392            }
16393        } else {
16394            synchronized (mPackages) {
16395                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16396                if (ps != null) {
16397                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16398                    if (res.removedInfo.removedChildPackages != null) {
16399                        final int childCount = res.removedInfo.removedChildPackages.size();
16400                        // Iterate in reverse as we may modify the collection
16401                        for (int i = childCount - 1; i >= 0; i--) {
16402                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16403                            if (res.addedChildPackages.containsKey(childPackageName)) {
16404                                res.removedInfo.removedChildPackages.removeAt(i);
16405                            } else {
16406                                PackageRemovedInfo childInfo = res.removedInfo
16407                                        .removedChildPackages.valueAt(i);
16408                                childInfo.removedForAllUsers = mPackages.get(
16409                                        childInfo.removedPackage) == null;
16410                            }
16411                        }
16412                    }
16413                }
16414            }
16415        }
16416    }
16417
16418    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16419            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16420            final @ScanFlags int scanFlags, UserHandle user,
16421            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16422            int installReason) {
16423        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16424                + ", old=" + deletedPackage);
16425
16426        final boolean disabledSystem;
16427
16428        // Remove existing system package
16429        removePackageLI(deletedPackage, true);
16430
16431        synchronized (mPackages) {
16432            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16433        }
16434        if (!disabledSystem) {
16435            // We didn't need to disable the .apk as a current system package,
16436            // which means we are replacing another update that is already
16437            // installed.  We need to make sure to delete the older one's .apk.
16438            res.removedInfo.args = createInstallArgsForExisting(0,
16439                    deletedPackage.applicationInfo.getCodePath(),
16440                    deletedPackage.applicationInfo.getResourcePath(),
16441                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16442        } else {
16443            res.removedInfo.args = null;
16444        }
16445
16446        // Successfully disabled the old package. Now proceed with re-installation
16447        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16448                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16449
16450        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16451        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16452                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16453
16454        PackageParser.Package newPackage = null;
16455        try {
16456            // Add the package to the internal data structures
16457            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16458
16459            // Set the update and install times
16460            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16461            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16462                    System.currentTimeMillis());
16463
16464            // Update the package dynamic state if succeeded
16465            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16466                // Now that the install succeeded make sure we remove data
16467                // directories for any child package the update removed.
16468                final int deletedChildCount = (deletedPackage.childPackages != null)
16469                        ? deletedPackage.childPackages.size() : 0;
16470                final int newChildCount = (newPackage.childPackages != null)
16471                        ? newPackage.childPackages.size() : 0;
16472                for (int i = 0; i < deletedChildCount; i++) {
16473                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16474                    boolean childPackageDeleted = true;
16475                    for (int j = 0; j < newChildCount; j++) {
16476                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16477                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16478                            childPackageDeleted = false;
16479                            break;
16480                        }
16481                    }
16482                    if (childPackageDeleted) {
16483                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16484                                deletedChildPkg.packageName);
16485                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16486                            PackageRemovedInfo removedChildRes = res.removedInfo
16487                                    .removedChildPackages.get(deletedChildPkg.packageName);
16488                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16489                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16490                        }
16491                    }
16492                }
16493
16494                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16495                        installReason);
16496                prepareAppDataAfterInstallLIF(newPackage);
16497
16498                mDexManager.notifyPackageUpdated(newPackage.packageName,
16499                            newPackage.baseCodePath, newPackage.splitCodePaths);
16500            }
16501        } catch (PackageManagerException e) {
16502            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16503            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16504        }
16505
16506        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16507            // Re installation failed. Restore old information
16508            // Remove new pkg information
16509            if (newPackage != null) {
16510                removeInstalledPackageLI(newPackage, true);
16511            }
16512            // Add back the old system package
16513            try {
16514                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16515            } catch (PackageManagerException e) {
16516                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16517            }
16518
16519            synchronized (mPackages) {
16520                if (disabledSystem) {
16521                    enableSystemPackageLPw(deletedPackage);
16522                }
16523
16524                // Ensure the installer package name up to date
16525                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16526
16527                // Update permissions for restored package
16528                mPermissionManager.updatePermissions(
16529                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16530                        mPermissionCallback);
16531
16532                mSettings.writeLPr();
16533            }
16534
16535            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16536                    + " after failed upgrade");
16537        }
16538    }
16539
16540    /**
16541     * Checks whether the parent or any of the child packages have a change shared
16542     * user. For a package to be a valid update the shred users of the parent and
16543     * the children should match. We may later support changing child shared users.
16544     * @param oldPkg The updated package.
16545     * @param newPkg The update package.
16546     * @return The shared user that change between the versions.
16547     */
16548    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16549            PackageParser.Package newPkg) {
16550        // Check parent shared user
16551        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16552            return newPkg.packageName;
16553        }
16554        // Check child shared users
16555        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16556        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16557        for (int i = 0; i < newChildCount; i++) {
16558            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16559            // If this child was present, did it have the same shared user?
16560            for (int j = 0; j < oldChildCount; j++) {
16561                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16562                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16563                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16564                    return newChildPkg.packageName;
16565                }
16566            }
16567        }
16568        return null;
16569    }
16570
16571    private void removeNativeBinariesLI(PackageSetting ps) {
16572        // Remove the lib path for the parent package
16573        if (ps != null) {
16574            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16575            // Remove the lib path for the child packages
16576            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16577            for (int i = 0; i < childCount; i++) {
16578                PackageSetting childPs = null;
16579                synchronized (mPackages) {
16580                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16581                }
16582                if (childPs != null) {
16583                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16584                            .legacyNativeLibraryPathString);
16585                }
16586            }
16587        }
16588    }
16589
16590    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16591        // Enable the parent package
16592        mSettings.enableSystemPackageLPw(pkg.packageName);
16593        // Enable the child packages
16594        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16595        for (int i = 0; i < childCount; i++) {
16596            PackageParser.Package childPkg = pkg.childPackages.get(i);
16597            mSettings.enableSystemPackageLPw(childPkg.packageName);
16598        }
16599    }
16600
16601    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16602            PackageParser.Package newPkg) {
16603        // Disable the parent package (parent always replaced)
16604        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16605        // Disable the child packages
16606        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16607        for (int i = 0; i < childCount; i++) {
16608            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16609            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16610            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16611        }
16612        return disabled;
16613    }
16614
16615    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16616            String installerPackageName) {
16617        // Enable the parent package
16618        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16619        // Enable the child packages
16620        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16621        for (int i = 0; i < childCount; i++) {
16622            PackageParser.Package childPkg = pkg.childPackages.get(i);
16623            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16624        }
16625    }
16626
16627    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16628            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16629        // Update the parent package setting
16630        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16631                res, user, installReason);
16632        // Update the child packages setting
16633        final int childCount = (newPackage.childPackages != null)
16634                ? newPackage.childPackages.size() : 0;
16635        for (int i = 0; i < childCount; i++) {
16636            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16637            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16638            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16639                    childRes.origUsers, childRes, user, installReason);
16640        }
16641    }
16642
16643    private void updateSettingsInternalLI(PackageParser.Package pkg,
16644            String installerPackageName, int[] allUsers, int[] installedForUsers,
16645            PackageInstalledInfo res, UserHandle user, int installReason) {
16646        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16647
16648        String pkgName = pkg.packageName;
16649        synchronized (mPackages) {
16650            //write settings. the installStatus will be incomplete at this stage.
16651            //note that the new package setting would have already been
16652            //added to mPackages. It hasn't been persisted yet.
16653            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16654            // TODO: Remove this write? It's also written at the end of this method
16655            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16656            mSettings.writeLPr();
16657            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16658        }
16659
16660        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16661        synchronized (mPackages) {
16662// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16663            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16664                    mPermissionCallback);
16665            // For system-bundled packages, we assume that installing an upgraded version
16666            // of the package implies that the user actually wants to run that new code,
16667            // so we enable the package.
16668            PackageSetting ps = mSettings.mPackages.get(pkgName);
16669            final int userId = user.getIdentifier();
16670            if (ps != null) {
16671                if (isSystemApp(pkg)) {
16672                    if (DEBUG_INSTALL) {
16673                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16674                    }
16675                    // Enable system package for requested users
16676                    if (res.origUsers != null) {
16677                        for (int origUserId : res.origUsers) {
16678                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16679                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16680                                        origUserId, installerPackageName);
16681                            }
16682                        }
16683                    }
16684                    // Also convey the prior install/uninstall state
16685                    if (allUsers != null && installedForUsers != null) {
16686                        for (int currentUserId : allUsers) {
16687                            final boolean installed = ArrayUtils.contains(
16688                                    installedForUsers, currentUserId);
16689                            if (DEBUG_INSTALL) {
16690                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16691                            }
16692                            ps.setInstalled(installed, currentUserId);
16693                        }
16694                        // these install state changes will be persisted in the
16695                        // upcoming call to mSettings.writeLPr().
16696                    }
16697                }
16698                // It's implied that when a user requests installation, they want the app to be
16699                // installed and enabled.
16700                if (userId != UserHandle.USER_ALL) {
16701                    ps.setInstalled(true, userId);
16702                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16703                }
16704
16705                // When replacing an existing package, preserve the original install reason for all
16706                // users that had the package installed before.
16707                final Set<Integer> previousUserIds = new ArraySet<>();
16708                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16709                    final int installReasonCount = res.removedInfo.installReasons.size();
16710                    for (int i = 0; i < installReasonCount; i++) {
16711                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16712                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16713                        ps.setInstallReason(previousInstallReason, previousUserId);
16714                        previousUserIds.add(previousUserId);
16715                    }
16716                }
16717
16718                // Set install reason for users that are having the package newly installed.
16719                if (userId == UserHandle.USER_ALL) {
16720                    for (int currentUserId : sUserManager.getUserIds()) {
16721                        if (!previousUserIds.contains(currentUserId)) {
16722                            ps.setInstallReason(installReason, currentUserId);
16723                        }
16724                    }
16725                } else if (!previousUserIds.contains(userId)) {
16726                    ps.setInstallReason(installReason, userId);
16727                }
16728                mSettings.writeKernelMappingLPr(ps);
16729            }
16730            res.name = pkgName;
16731            res.uid = pkg.applicationInfo.uid;
16732            res.pkg = pkg;
16733            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16734            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16735            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16736            //to update install status
16737            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16738            mSettings.writeLPr();
16739            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16740        }
16741
16742        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16743    }
16744
16745    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16746        try {
16747            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16748            installPackageLI(args, res);
16749        } finally {
16750            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16751        }
16752    }
16753
16754    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16755        final int installFlags = args.installFlags;
16756        final String installerPackageName = args.installerPackageName;
16757        final String volumeUuid = args.volumeUuid;
16758        final File tmpPackageFile = new File(args.getCodePath());
16759        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16760        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16761                || (args.volumeUuid != null));
16762        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16763        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16764        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16765        final boolean virtualPreload =
16766                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16767        boolean replace = false;
16768        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16769        if (args.move != null) {
16770            // moving a complete application; perform an initial scan on the new install location
16771            scanFlags |= SCAN_INITIAL;
16772        }
16773        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16774            scanFlags |= SCAN_DONT_KILL_APP;
16775        }
16776        if (instantApp) {
16777            scanFlags |= SCAN_AS_INSTANT_APP;
16778        }
16779        if (fullApp) {
16780            scanFlags |= SCAN_AS_FULL_APP;
16781        }
16782        if (virtualPreload) {
16783            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16784        }
16785
16786        // Result object to be returned
16787        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16788        res.installerPackageName = installerPackageName;
16789
16790        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16791
16792        // Sanity check
16793        if (instantApp && (forwardLocked || onExternal)) {
16794            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16795                    + " external=" + onExternal);
16796            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16797            return;
16798        }
16799
16800        // Retrieve PackageSettings and parse package
16801        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16802                | PackageParser.PARSE_ENFORCE_CODE
16803                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16804                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16805                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16806        PackageParser pp = new PackageParser();
16807        pp.setSeparateProcesses(mSeparateProcesses);
16808        pp.setDisplayMetrics(mMetrics);
16809        pp.setCallback(mPackageParserCallback);
16810
16811        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16812        final PackageParser.Package pkg;
16813        try {
16814            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16815            DexMetadataHelper.validatePackageDexMetadata(pkg);
16816        } catch (PackageParserException e) {
16817            res.setError("Failed parse during installPackageLI", e);
16818            return;
16819        } finally {
16820            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16821        }
16822
16823        // Instant apps have several additional install-time checks.
16824        if (instantApp) {
16825            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16826                Slog.w(TAG,
16827                        "Instant app package " + pkg.packageName + " does not target at least O");
16828                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16829                        "Instant app package must target at least O");
16830                return;
16831            }
16832            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16833                Slog.w(TAG, "Instant app package " + pkg.packageName
16834                        + " does not target targetSandboxVersion 2");
16835                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16836                        "Instant app package must use targetSandboxVersion 2");
16837                return;
16838            }
16839            if (pkg.mSharedUserId != null) {
16840                Slog.w(TAG, "Instant app package " + pkg.packageName
16841                        + " may not declare sharedUserId.");
16842                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16843                        "Instant app package may not declare a sharedUserId");
16844                return;
16845            }
16846        }
16847
16848        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16849            // Static shared libraries have synthetic package names
16850            renameStaticSharedLibraryPackage(pkg);
16851
16852            // No static shared libs on external storage
16853            if (onExternal) {
16854                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16855                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16856                        "Packages declaring static-shared libs cannot be updated");
16857                return;
16858            }
16859        }
16860
16861        // If we are installing a clustered package add results for the children
16862        if (pkg.childPackages != null) {
16863            synchronized (mPackages) {
16864                final int childCount = pkg.childPackages.size();
16865                for (int i = 0; i < childCount; i++) {
16866                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16867                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16868                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16869                    childRes.pkg = childPkg;
16870                    childRes.name = childPkg.packageName;
16871                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16872                    if (childPs != null) {
16873                        childRes.origUsers = childPs.queryInstalledUsers(
16874                                sUserManager.getUserIds(), true);
16875                    }
16876                    if ((mPackages.containsKey(childPkg.packageName))) {
16877                        childRes.removedInfo = new PackageRemovedInfo(this);
16878                        childRes.removedInfo.removedPackage = childPkg.packageName;
16879                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16880                    }
16881                    if (res.addedChildPackages == null) {
16882                        res.addedChildPackages = new ArrayMap<>();
16883                    }
16884                    res.addedChildPackages.put(childPkg.packageName, childRes);
16885                }
16886            }
16887        }
16888
16889        // If package doesn't declare API override, mark that we have an install
16890        // time CPU ABI override.
16891        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16892            pkg.cpuAbiOverride = args.abiOverride;
16893        }
16894
16895        String pkgName = res.name = pkg.packageName;
16896        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16897            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16898                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16899                return;
16900            }
16901        }
16902
16903        try {
16904            // either use what we've been given or parse directly from the APK
16905            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16906                pkg.setSigningDetails(args.signingDetails);
16907            } else {
16908                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16909            }
16910        } catch (PackageParserException e) {
16911            res.setError("Failed collect during installPackageLI", e);
16912            return;
16913        }
16914
16915        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16916                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16917            Slog.w(TAG, "Instant app package " + pkg.packageName
16918                    + " is not signed with at least APK Signature Scheme v2");
16919            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16920                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16921            return;
16922        }
16923
16924        // Get rid of all references to package scan path via parser.
16925        pp = null;
16926        String oldCodePath = null;
16927        boolean systemApp = false;
16928        synchronized (mPackages) {
16929            // Check if installing already existing package
16930            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16931                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16932                if (pkg.mOriginalPackages != null
16933                        && pkg.mOriginalPackages.contains(oldName)
16934                        && mPackages.containsKey(oldName)) {
16935                    // This package is derived from an original package,
16936                    // and this device has been updating from that original
16937                    // name.  We must continue using the original name, so
16938                    // rename the new package here.
16939                    pkg.setPackageName(oldName);
16940                    pkgName = pkg.packageName;
16941                    replace = true;
16942                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16943                            + oldName + " pkgName=" + pkgName);
16944                } else if (mPackages.containsKey(pkgName)) {
16945                    // This package, under its official name, already exists
16946                    // on the device; we should replace it.
16947                    replace = true;
16948                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16949                }
16950
16951                // Child packages are installed through the parent package
16952                if (pkg.parentPackage != null) {
16953                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16954                            "Package " + pkg.packageName + " is child of package "
16955                                    + pkg.parentPackage.parentPackage + ". Child packages "
16956                                    + "can be updated only through the parent package.");
16957                    return;
16958                }
16959
16960                if (replace) {
16961                    // Prevent apps opting out from runtime permissions
16962                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16963                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16964                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16965                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16966                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16967                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16968                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16969                                        + " doesn't support runtime permissions but the old"
16970                                        + " target SDK " + oldTargetSdk + " does.");
16971                        return;
16972                    }
16973                    // Prevent persistent apps from being updated
16974                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16975                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16976                                "Package " + oldPackage.packageName + " is a persistent app. "
16977                                        + "Persistent apps are not updateable.");
16978                        return;
16979                    }
16980                    // Prevent apps from downgrading their targetSandbox.
16981                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16982                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16983                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16984                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16985                                "Package " + pkg.packageName + " new target sandbox "
16986                                + newTargetSandbox + " is incompatible with the previous value of"
16987                                + oldTargetSandbox + ".");
16988                        return;
16989                    }
16990
16991                    // Prevent installing of child packages
16992                    if (oldPackage.parentPackage != null) {
16993                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16994                                "Package " + pkg.packageName + " is child of package "
16995                                        + oldPackage.parentPackage + ". Child packages "
16996                                        + "can be updated only through the parent package.");
16997                        return;
16998                    }
16999                }
17000            }
17001
17002            PackageSetting ps = mSettings.mPackages.get(pkgName);
17003            if (ps != null) {
17004                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17005
17006                // Static shared libs have same package with different versions where
17007                // we internally use a synthetic package name to allow multiple versions
17008                // of the same package, therefore we need to compare signatures against
17009                // the package setting for the latest library version.
17010                PackageSetting signatureCheckPs = ps;
17011                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17012                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17013                    if (libraryEntry != null) {
17014                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17015                    }
17016                }
17017
17018                // Quick sanity check that we're signed correctly if updating;
17019                // we'll check this again later when scanning, but we want to
17020                // bail early here before tripping over redefined permissions.
17021                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17022                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17023                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17024                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17025                                + pkg.packageName + " upgrade keys do not match the "
17026                                + "previously installed version");
17027                        return;
17028                    }
17029                } else {
17030                    try {
17031                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17032                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17033                        // We don't care about disabledPkgSetting on install for now.
17034                        final boolean compatMatch = verifySignatures(
17035                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17036                                compareRecover);
17037                        // The new KeySets will be re-added later in the scanning process.
17038                        if (compatMatch) {
17039                            synchronized (mPackages) {
17040                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17041                            }
17042                        }
17043                    } catch (PackageManagerException e) {
17044                        res.setError(e.error, e.getMessage());
17045                        return;
17046                    }
17047                }
17048
17049                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17050                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17051                    systemApp = (ps.pkg.applicationInfo.flags &
17052                            ApplicationInfo.FLAG_SYSTEM) != 0;
17053                }
17054                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17055            }
17056
17057            int N = pkg.permissions.size();
17058            for (int i = N-1; i >= 0; i--) {
17059                final PackageParser.Permission perm = pkg.permissions.get(i);
17060                final BasePermission bp =
17061                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17062
17063                // Don't allow anyone but the system to define ephemeral permissions.
17064                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17065                        && !systemApp) {
17066                    Slog.w(TAG, "Non-System package " + pkg.packageName
17067                            + " attempting to delcare ephemeral permission "
17068                            + perm.info.name + "; Removing ephemeral.");
17069                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17070                }
17071
17072                // Check whether the newly-scanned package wants to define an already-defined perm
17073                if (bp != null) {
17074                    // If the defining package is signed with our cert, it's okay.  This
17075                    // also includes the "updating the same package" case, of course.
17076                    // "updating same package" could also involve key-rotation.
17077                    final boolean sigsOk;
17078                    final String sourcePackageName = bp.getSourcePackageName();
17079                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17080                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17081                    if (sourcePackageName.equals(pkg.packageName)
17082                            && (ksms.shouldCheckUpgradeKeySetLocked(
17083                                    sourcePackageSetting, scanFlags))) {
17084                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17085                    } else {
17086
17087                        // in the event of signing certificate rotation, we need to see if the
17088                        // package's certificate has rotated from the current one, or if it is an
17089                        // older certificate with which the current is ok with sharing permissions
17090                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17091                                        pkg.mSigningDetails,
17092                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17093                            sigsOk = true;
17094                        } else if (pkg.mSigningDetails.checkCapability(
17095                                        sourcePackageSetting.signatures.mSigningDetails,
17096                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17097
17098                            // the scanned package checks out, has signing certificate rotation
17099                            // history, and is newer; bring it over
17100                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17101                            sigsOk = true;
17102                        } else {
17103                            sigsOk = false;
17104                        }
17105                    }
17106                    if (!sigsOk) {
17107                        // If the owning package is the system itself, we log but allow
17108                        // install to proceed; we fail the install on all other permission
17109                        // redefinitions.
17110                        if (!sourcePackageName.equals("android")) {
17111                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17112                                    + pkg.packageName + " attempting to redeclare permission "
17113                                    + perm.info.name + " already owned by " + sourcePackageName);
17114                            res.origPermission = perm.info.name;
17115                            res.origPackage = sourcePackageName;
17116                            return;
17117                        } else {
17118                            Slog.w(TAG, "Package " + pkg.packageName
17119                                    + " attempting to redeclare system permission "
17120                                    + perm.info.name + "; ignoring new declaration");
17121                            pkg.permissions.remove(i);
17122                        }
17123                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17124                        // Prevent apps to change protection level to dangerous from any other
17125                        // type as this would allow a privilege escalation where an app adds a
17126                        // normal/signature permission in other app's group and later redefines
17127                        // it as dangerous leading to the group auto-grant.
17128                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17129                                == PermissionInfo.PROTECTION_DANGEROUS) {
17130                            if (bp != null && !bp.isRuntime()) {
17131                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17132                                        + "non-runtime permission " + perm.info.name
17133                                        + " to runtime; keeping old protection level");
17134                                perm.info.protectionLevel = bp.getProtectionLevel();
17135                            }
17136                        }
17137                    }
17138                }
17139            }
17140        }
17141
17142        if (systemApp) {
17143            if (onExternal) {
17144                // Abort update; system app can't be replaced with app on sdcard
17145                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17146                        "Cannot install updates to system apps on sdcard");
17147                return;
17148            } else if (instantApp) {
17149                // Abort update; system app can't be replaced with an instant app
17150                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17151                        "Cannot update a system app with an instant app");
17152                return;
17153            }
17154        }
17155
17156        if (args.move != null) {
17157            // We did an in-place move, so dex is ready to roll
17158            scanFlags |= SCAN_NO_DEX;
17159            scanFlags |= SCAN_MOVE;
17160
17161            synchronized (mPackages) {
17162                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17163                if (ps == null) {
17164                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17165                            "Missing settings for moved package " + pkgName);
17166                }
17167
17168                // We moved the entire application as-is, so bring over the
17169                // previously derived ABI information.
17170                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17171                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17172            }
17173
17174        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17175            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17176            scanFlags |= SCAN_NO_DEX;
17177
17178            try {
17179                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17180                    args.abiOverride : pkg.cpuAbiOverride);
17181                final boolean extractNativeLibs = !pkg.isLibrary();
17182                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17183            } catch (PackageManagerException pme) {
17184                Slog.e(TAG, "Error deriving application ABI", pme);
17185                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17186                return;
17187            }
17188
17189            // Shared libraries for the package need to be updated.
17190            synchronized (mPackages) {
17191                try {
17192                    updateSharedLibrariesLPr(pkg, null);
17193                } catch (PackageManagerException e) {
17194                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17195                }
17196            }
17197        }
17198
17199        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17200            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17201            return;
17202        }
17203
17204        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17205            String apkPath = null;
17206            synchronized (mPackages) {
17207                // Note that if the attacker managed to skip verify setup, for example by tampering
17208                // with the package settings, upon reboot we will do full apk verification when
17209                // verity is not detected.
17210                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17211                if (ps != null && ps.isPrivileged()) {
17212                    apkPath = pkg.baseCodePath;
17213                }
17214            }
17215
17216            if (apkPath != null) {
17217                final VerityUtils.SetupResult result =
17218                        VerityUtils.generateApkVeritySetupData(apkPath);
17219                if (result.isOk()) {
17220                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17221                    FileDescriptor fd = result.getUnownedFileDescriptor();
17222                    try {
17223                        mInstaller.installApkVerity(apkPath, fd);
17224                    } catch (InstallerException e) {
17225                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17226                                "Failed to set up verity: " + e);
17227                        return;
17228                    } finally {
17229                        IoUtils.closeQuietly(fd);
17230                    }
17231                } else if (result.isFailed()) {
17232                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17233                    return;
17234                } else {
17235                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17236                    // reboot.
17237                }
17238            }
17239        }
17240
17241        if (!instantApp) {
17242            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17243        } else {
17244            if (DEBUG_DOMAIN_VERIFICATION) {
17245                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17246            }
17247        }
17248
17249        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17250                "installPackageLI")) {
17251            if (replace) {
17252                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17253                    // Static libs have a synthetic package name containing the version
17254                    // and cannot be updated as an update would get a new package name,
17255                    // unless this is the exact same version code which is useful for
17256                    // development.
17257                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17258                    if (existingPkg != null &&
17259                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17260                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17261                                + "static-shared libs cannot be updated");
17262                        return;
17263                    }
17264                }
17265                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17266                        installerPackageName, res, args.installReason);
17267            } else {
17268                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17269                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17270            }
17271        }
17272
17273        // Prepare the application profiles for the new code paths.
17274        // This needs to be done before invoking dexopt so that any install-time profile
17275        // can be used for optimizations.
17276        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17277
17278        // Check whether we need to dexopt the app.
17279        //
17280        // NOTE: it is IMPORTANT to call dexopt:
17281        //   - after doRename which will sync the package data from PackageParser.Package and its
17282        //     corresponding ApplicationInfo.
17283        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17284        //     uid of the application (pkg.applicationInfo.uid).
17285        //     This update happens in place!
17286        //
17287        // We only need to dexopt if the package meets ALL of the following conditions:
17288        //   1) it is not forward locked.
17289        //   2) it is not on on an external ASEC container.
17290        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17291        //
17292        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17293        // complete, so we skip this step during installation. Instead, we'll take extra time
17294        // the first time the instant app starts. It's preferred to do it this way to provide
17295        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17296        // middle of running an instant app. The default behaviour can be overridden
17297        // via gservices.
17298        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17299                && !forwardLocked
17300                && !pkg.applicationInfo.isExternalAsec()
17301                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17302                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17303
17304        if (performDexopt) {
17305            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17306            // Do not run PackageDexOptimizer through the local performDexOpt
17307            // method because `pkg` may not be in `mPackages` yet.
17308            //
17309            // Also, don't fail application installs if the dexopt step fails.
17310            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17311                    REASON_INSTALL,
17312                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17313                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17314            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17315                    null /* instructionSets */,
17316                    getOrCreateCompilerPackageStats(pkg),
17317                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17318                    dexoptOptions);
17319            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17320        }
17321
17322        // Notify BackgroundDexOptService that the package has been changed.
17323        // If this is an update of a package which used to fail to compile,
17324        // BackgroundDexOptService will remove it from its blacklist.
17325        // TODO: Layering violation
17326        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17327
17328        synchronized (mPackages) {
17329            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17330            if (ps != null) {
17331                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17332                ps.setUpdateAvailable(false /*updateAvailable*/);
17333            }
17334
17335            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17336            for (int i = 0; i < childCount; i++) {
17337                PackageParser.Package childPkg = pkg.childPackages.get(i);
17338                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17339                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17340                if (childPs != null) {
17341                    childRes.newUsers = childPs.queryInstalledUsers(
17342                            sUserManager.getUserIds(), true);
17343                }
17344            }
17345
17346            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17347                updateSequenceNumberLP(ps, res.newUsers);
17348                updateInstantAppInstallerLocked(pkgName);
17349            }
17350        }
17351    }
17352
17353    private void startIntentFilterVerifications(int userId, boolean replacing,
17354            PackageParser.Package pkg) {
17355        if (mIntentFilterVerifierComponent == null) {
17356            Slog.w(TAG, "No IntentFilter verification will not be done as "
17357                    + "there is no IntentFilterVerifier available!");
17358            return;
17359        }
17360
17361        final int verifierUid = getPackageUid(
17362                mIntentFilterVerifierComponent.getPackageName(),
17363                MATCH_DEBUG_TRIAGED_MISSING,
17364                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17365
17366        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17367        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17368        mHandler.sendMessage(msg);
17369
17370        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17371        for (int i = 0; i < childCount; i++) {
17372            PackageParser.Package childPkg = pkg.childPackages.get(i);
17373            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17374            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17375            mHandler.sendMessage(msg);
17376        }
17377    }
17378
17379    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17380            PackageParser.Package pkg) {
17381        int size = pkg.activities.size();
17382        if (size == 0) {
17383            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17384                    "No activity, so no need to verify any IntentFilter!");
17385            return;
17386        }
17387
17388        final boolean hasDomainURLs = hasDomainURLs(pkg);
17389        if (!hasDomainURLs) {
17390            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17391                    "No domain URLs, so no need to verify any IntentFilter!");
17392            return;
17393        }
17394
17395        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17396                + " if any IntentFilter from the " + size
17397                + " Activities needs verification ...");
17398
17399        int count = 0;
17400        final String packageName = pkg.packageName;
17401
17402        synchronized (mPackages) {
17403            // If this is a new install and we see that we've already run verification for this
17404            // package, we have nothing to do: it means the state was restored from backup.
17405            if (!replacing) {
17406                IntentFilterVerificationInfo ivi =
17407                        mSettings.getIntentFilterVerificationLPr(packageName);
17408                if (ivi != null) {
17409                    if (DEBUG_DOMAIN_VERIFICATION) {
17410                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17411                                + ivi.getStatusString());
17412                    }
17413                    return;
17414                }
17415            }
17416
17417            // If any filters need to be verified, then all need to be.
17418            boolean needToVerify = false;
17419            for (PackageParser.Activity a : pkg.activities) {
17420                for (ActivityIntentInfo filter : a.intents) {
17421                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17422                        if (DEBUG_DOMAIN_VERIFICATION) {
17423                            Slog.d(TAG,
17424                                    "Intent filter needs verification, so processing all filters");
17425                        }
17426                        needToVerify = true;
17427                        break;
17428                    }
17429                }
17430            }
17431
17432            if (needToVerify) {
17433                final int verificationId = mIntentFilterVerificationToken++;
17434                for (PackageParser.Activity a : pkg.activities) {
17435                    for (ActivityIntentInfo filter : a.intents) {
17436                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17437                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17438                                    "Verification needed for IntentFilter:" + filter.toString());
17439                            mIntentFilterVerifier.addOneIntentFilterVerification(
17440                                    verifierUid, userId, verificationId, filter, packageName);
17441                            count++;
17442                        }
17443                    }
17444                }
17445            }
17446        }
17447
17448        if (count > 0) {
17449            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17450                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17451                    +  " for userId:" + userId);
17452            mIntentFilterVerifier.startVerifications(userId);
17453        } else {
17454            if (DEBUG_DOMAIN_VERIFICATION) {
17455                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17456            }
17457        }
17458    }
17459
17460    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17461        final ComponentName cn  = filter.activity.getComponentName();
17462        final String packageName = cn.getPackageName();
17463
17464        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17465                packageName);
17466        if (ivi == null) {
17467            return true;
17468        }
17469        int status = ivi.getStatus();
17470        switch (status) {
17471            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17472            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17473                return true;
17474
17475            default:
17476                // Nothing to do
17477                return false;
17478        }
17479    }
17480
17481    private static boolean isMultiArch(ApplicationInfo info) {
17482        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17483    }
17484
17485    private static boolean isExternal(PackageParser.Package pkg) {
17486        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17487    }
17488
17489    private static boolean isExternal(PackageSetting ps) {
17490        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17491    }
17492
17493    private static boolean isSystemApp(PackageParser.Package pkg) {
17494        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17495    }
17496
17497    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17498        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17499    }
17500
17501    private static boolean isOemApp(PackageParser.Package pkg) {
17502        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17503    }
17504
17505    private static boolean isVendorApp(PackageParser.Package pkg) {
17506        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17507    }
17508
17509    private static boolean isProductApp(PackageParser.Package pkg) {
17510        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17511    }
17512
17513    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17514        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17515    }
17516
17517    private static boolean isSystemApp(PackageSetting ps) {
17518        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17519    }
17520
17521    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17522        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17523    }
17524
17525    private int packageFlagsToInstallFlags(PackageSetting ps) {
17526        int installFlags = 0;
17527        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17528            // This existing package was an external ASEC install when we have
17529            // the external flag without a UUID
17530            installFlags |= PackageManager.INSTALL_EXTERNAL;
17531        }
17532        if (ps.isForwardLocked()) {
17533            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17534        }
17535        return installFlags;
17536    }
17537
17538    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17539        if (isExternal(pkg)) {
17540            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17541                return mSettings.getExternalVersion();
17542            } else {
17543                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17544            }
17545        } else {
17546            return mSettings.getInternalVersion();
17547        }
17548    }
17549
17550    private void deleteTempPackageFiles() {
17551        final FilenameFilter filter = new FilenameFilter() {
17552            public boolean accept(File dir, String name) {
17553                return name.startsWith("vmdl") && name.endsWith(".tmp");
17554            }
17555        };
17556        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17557            file.delete();
17558        }
17559    }
17560
17561    @Override
17562    public void deletePackageAsUser(String packageName, int versionCode,
17563            IPackageDeleteObserver observer, int userId, int flags) {
17564        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17565                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17566    }
17567
17568    @Override
17569    public void deletePackageVersioned(VersionedPackage versionedPackage,
17570            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17571        final int callingUid = Binder.getCallingUid();
17572        mContext.enforceCallingOrSelfPermission(
17573                android.Manifest.permission.DELETE_PACKAGES, null);
17574        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17575        Preconditions.checkNotNull(versionedPackage);
17576        Preconditions.checkNotNull(observer);
17577        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17578                PackageManager.VERSION_CODE_HIGHEST,
17579                Long.MAX_VALUE, "versionCode must be >= -1");
17580
17581        final String packageName = versionedPackage.getPackageName();
17582        final long versionCode = versionedPackage.getLongVersionCode();
17583        final String internalPackageName;
17584        synchronized (mPackages) {
17585            // Normalize package name to handle renamed packages and static libs
17586            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17587        }
17588
17589        final int uid = Binder.getCallingUid();
17590        if (!isOrphaned(internalPackageName)
17591                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17592            try {
17593                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17594                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17595                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17596                observer.onUserActionRequired(intent);
17597            } catch (RemoteException re) {
17598            }
17599            return;
17600        }
17601        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17602        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17603        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17604            mContext.enforceCallingOrSelfPermission(
17605                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17606                    "deletePackage for user " + userId);
17607        }
17608
17609        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17610            try {
17611                observer.onPackageDeleted(packageName,
17612                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17613            } catch (RemoteException re) {
17614            }
17615            return;
17616        }
17617
17618        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17619            try {
17620                observer.onPackageDeleted(packageName,
17621                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17622            } catch (RemoteException re) {
17623            }
17624            return;
17625        }
17626
17627        if (DEBUG_REMOVE) {
17628            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17629                    + " deleteAllUsers: " + deleteAllUsers + " version="
17630                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17631                    ? "VERSION_CODE_HIGHEST" : versionCode));
17632        }
17633        // Queue up an async operation since the package deletion may take a little while.
17634        mHandler.post(new Runnable() {
17635            public void run() {
17636                mHandler.removeCallbacks(this);
17637                int returnCode;
17638                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17639                boolean doDeletePackage = true;
17640                if (ps != null) {
17641                    final boolean targetIsInstantApp =
17642                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17643                    doDeletePackage = !targetIsInstantApp
17644                            || canViewInstantApps;
17645                }
17646                if (doDeletePackage) {
17647                    if (!deleteAllUsers) {
17648                        returnCode = deletePackageX(internalPackageName, versionCode,
17649                                userId, deleteFlags);
17650                    } else {
17651                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17652                                internalPackageName, users);
17653                        // If nobody is blocking uninstall, proceed with delete for all users
17654                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17655                            returnCode = deletePackageX(internalPackageName, versionCode,
17656                                    userId, deleteFlags);
17657                        } else {
17658                            // Otherwise uninstall individually for users with blockUninstalls=false
17659                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17660                            for (int userId : users) {
17661                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17662                                    returnCode = deletePackageX(internalPackageName, versionCode,
17663                                            userId, userFlags);
17664                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17665                                        Slog.w(TAG, "Package delete failed for user " + userId
17666                                                + ", returnCode " + returnCode);
17667                                    }
17668                                }
17669                            }
17670                            // The app has only been marked uninstalled for certain users.
17671                            // We still need to report that delete was blocked
17672                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17673                        }
17674                    }
17675                } else {
17676                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17677                }
17678                try {
17679                    observer.onPackageDeleted(packageName, returnCode, null);
17680                } catch (RemoteException e) {
17681                    Log.i(TAG, "Observer no longer exists.");
17682                } //end catch
17683            } //end run
17684        });
17685    }
17686
17687    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17688        if (pkg.staticSharedLibName != null) {
17689            return pkg.manifestPackageName;
17690        }
17691        return pkg.packageName;
17692    }
17693
17694    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17695        // Handle renamed packages
17696        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17697        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17698
17699        // Is this a static library?
17700        LongSparseArray<SharedLibraryEntry> versionedLib =
17701                mStaticLibsByDeclaringPackage.get(packageName);
17702        if (versionedLib == null || versionedLib.size() <= 0) {
17703            return packageName;
17704        }
17705
17706        // Figure out which lib versions the caller can see
17707        LongSparseLongArray versionsCallerCanSee = null;
17708        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17709        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17710                && callingAppId != Process.ROOT_UID) {
17711            versionsCallerCanSee = new LongSparseLongArray();
17712            String libName = versionedLib.valueAt(0).info.getName();
17713            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17714            if (uidPackages != null) {
17715                for (String uidPackage : uidPackages) {
17716                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17717                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17718                    if (libIdx >= 0) {
17719                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17720                        versionsCallerCanSee.append(libVersion, libVersion);
17721                    }
17722                }
17723            }
17724        }
17725
17726        // Caller can see nothing - done
17727        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17728            return packageName;
17729        }
17730
17731        // Find the version the caller can see and the app version code
17732        SharedLibraryEntry highestVersion = null;
17733        final int versionCount = versionedLib.size();
17734        for (int i = 0; i < versionCount; i++) {
17735            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17736            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17737                    libEntry.info.getLongVersion()) < 0) {
17738                continue;
17739            }
17740            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17741            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17742                if (libVersionCode == versionCode) {
17743                    return libEntry.apk;
17744                }
17745            } else if (highestVersion == null) {
17746                highestVersion = libEntry;
17747            } else if (libVersionCode  > highestVersion.info
17748                    .getDeclaringPackage().getLongVersionCode()) {
17749                highestVersion = libEntry;
17750            }
17751        }
17752
17753        if (highestVersion != null) {
17754            return highestVersion.apk;
17755        }
17756
17757        return packageName;
17758    }
17759
17760    boolean isCallerVerifier(int callingUid) {
17761        final int callingUserId = UserHandle.getUserId(callingUid);
17762        return mRequiredVerifierPackage != null &&
17763                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17764    }
17765
17766    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17767        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17768              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17769            return true;
17770        }
17771        final int callingUserId = UserHandle.getUserId(callingUid);
17772        // If the caller installed the pkgName, then allow it to silently uninstall.
17773        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17774            return true;
17775        }
17776
17777        // Allow package verifier to silently uninstall.
17778        if (mRequiredVerifierPackage != null &&
17779                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17780            return true;
17781        }
17782
17783        // Allow package uninstaller to silently uninstall.
17784        if (mRequiredUninstallerPackage != null &&
17785                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17786            return true;
17787        }
17788
17789        // Allow storage manager to silently uninstall.
17790        if (mStorageManagerPackage != null &&
17791                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17792            return true;
17793        }
17794
17795        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17796        // uninstall for device owner provisioning.
17797        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17798                == PERMISSION_GRANTED) {
17799            return true;
17800        }
17801
17802        return false;
17803    }
17804
17805    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17806        int[] result = EMPTY_INT_ARRAY;
17807        for (int userId : userIds) {
17808            if (getBlockUninstallForUser(packageName, userId)) {
17809                result = ArrayUtils.appendInt(result, userId);
17810            }
17811        }
17812        return result;
17813    }
17814
17815    @Override
17816    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17817        final int callingUid = Binder.getCallingUid();
17818        if (getInstantAppPackageName(callingUid) != null
17819                && !isCallerSameApp(packageName, callingUid)) {
17820            return false;
17821        }
17822        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17823    }
17824
17825    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17826        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17827                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17828        try {
17829            if (dpm != null) {
17830                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17831                        /* callingUserOnly =*/ false);
17832                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17833                        : deviceOwnerComponentName.getPackageName();
17834                // Does the package contains the device owner?
17835                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17836                // this check is probably not needed, since DO should be registered as a device
17837                // admin on some user too. (Original bug for this: b/17657954)
17838                if (packageName.equals(deviceOwnerPackageName)) {
17839                    return true;
17840                }
17841                // Does it contain a device admin for any user?
17842                int[] users;
17843                if (userId == UserHandle.USER_ALL) {
17844                    users = sUserManager.getUserIds();
17845                } else {
17846                    users = new int[]{userId};
17847                }
17848                for (int i = 0; i < users.length; ++i) {
17849                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17850                        return true;
17851                    }
17852                }
17853            }
17854        } catch (RemoteException e) {
17855        }
17856        return false;
17857    }
17858
17859    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17860        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17861    }
17862
17863    /**
17864     *  This method is an internal method that could be get invoked either
17865     *  to delete an installed package or to clean up a failed installation.
17866     *  After deleting an installed package, a broadcast is sent to notify any
17867     *  listeners that the package has been removed. For cleaning up a failed
17868     *  installation, the broadcast is not necessary since the package's
17869     *  installation wouldn't have sent the initial broadcast either
17870     *  The key steps in deleting a package are
17871     *  deleting the package information in internal structures like mPackages,
17872     *  deleting the packages base directories through installd
17873     *  updating mSettings to reflect current status
17874     *  persisting settings for later use
17875     *  sending a broadcast if necessary
17876     */
17877    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17878        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17879        final boolean res;
17880
17881        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17882                ? UserHandle.USER_ALL : userId;
17883
17884        if (isPackageDeviceAdmin(packageName, removeUser)) {
17885            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17886            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17887        }
17888
17889        PackageSetting uninstalledPs = null;
17890        PackageParser.Package pkg = null;
17891
17892        // for the uninstall-updates case and restricted profiles, remember the per-
17893        // user handle installed state
17894        int[] allUsers;
17895        synchronized (mPackages) {
17896            uninstalledPs = mSettings.mPackages.get(packageName);
17897            if (uninstalledPs == null) {
17898                Slog.w(TAG, "Not removing non-existent package " + packageName);
17899                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17900            }
17901
17902            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17903                    && uninstalledPs.versionCode != versionCode) {
17904                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17905                        + uninstalledPs.versionCode + " != " + versionCode);
17906                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17907            }
17908
17909            // Static shared libs can be declared by any package, so let us not
17910            // allow removing a package if it provides a lib others depend on.
17911            pkg = mPackages.get(packageName);
17912
17913            allUsers = sUserManager.getUserIds();
17914
17915            if (pkg != null && pkg.staticSharedLibName != null) {
17916                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17917                        pkg.staticSharedLibVersion);
17918                if (libEntry != null) {
17919                    for (int currUserId : allUsers) {
17920                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17921                            continue;
17922                        }
17923                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17924                                libEntry.info, 0, currUserId);
17925                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17926                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17927                                    + " hosting lib " + libEntry.info.getName() + " version "
17928                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17929                                    + " for user " + currUserId);
17930                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17931                        }
17932                    }
17933                }
17934            }
17935
17936            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17937        }
17938
17939        final int freezeUser;
17940        if (isUpdatedSystemApp(uninstalledPs)
17941                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17942            // We're downgrading a system app, which will apply to all users, so
17943            // freeze them all during the downgrade
17944            freezeUser = UserHandle.USER_ALL;
17945        } else {
17946            freezeUser = removeUser;
17947        }
17948
17949        synchronized (mInstallLock) {
17950            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17951            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17952                    deleteFlags, "deletePackageX")) {
17953                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17954                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17955            }
17956            synchronized (mPackages) {
17957                if (res) {
17958                    if (pkg != null) {
17959                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17960                    }
17961                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17962                    updateInstantAppInstallerLocked(packageName);
17963                }
17964            }
17965        }
17966
17967        if (res) {
17968            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17969            info.sendPackageRemovedBroadcasts(killApp);
17970            info.sendSystemPackageUpdatedBroadcasts();
17971            info.sendSystemPackageAppearedBroadcasts();
17972        }
17973        // Force a gc here.
17974        Runtime.getRuntime().gc();
17975        // Delete the resources here after sending the broadcast to let
17976        // other processes clean up before deleting resources.
17977        if (info.args != null) {
17978            synchronized (mInstallLock) {
17979                info.args.doPostDeleteLI(true);
17980            }
17981        }
17982
17983        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17984    }
17985
17986    static class PackageRemovedInfo {
17987        final PackageSender packageSender;
17988        String removedPackage;
17989        String installerPackageName;
17990        int uid = -1;
17991        int removedAppId = -1;
17992        int[] origUsers;
17993        int[] removedUsers = null;
17994        int[] broadcastUsers = null;
17995        int[] instantUserIds = null;
17996        SparseArray<Integer> installReasons;
17997        boolean isRemovedPackageSystemUpdate = false;
17998        boolean isUpdate;
17999        boolean dataRemoved;
18000        boolean removedForAllUsers;
18001        boolean isStaticSharedLib;
18002        // Clean up resources deleted packages.
18003        InstallArgs args = null;
18004        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18005        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18006
18007        PackageRemovedInfo(PackageSender packageSender) {
18008            this.packageSender = packageSender;
18009        }
18010
18011        void sendPackageRemovedBroadcasts(boolean killApp) {
18012            sendPackageRemovedBroadcastInternal(killApp);
18013            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18014            for (int i = 0; i < childCount; i++) {
18015                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18016                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18017            }
18018        }
18019
18020        void sendSystemPackageUpdatedBroadcasts() {
18021            if (isRemovedPackageSystemUpdate) {
18022                sendSystemPackageUpdatedBroadcastsInternal();
18023                final int childCount = (removedChildPackages != null)
18024                        ? removedChildPackages.size() : 0;
18025                for (int i = 0; i < childCount; i++) {
18026                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18027                    if (childInfo.isRemovedPackageSystemUpdate) {
18028                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18029                    }
18030                }
18031            }
18032        }
18033
18034        void sendSystemPackageAppearedBroadcasts() {
18035            final int packageCount = (appearedChildPackages != null)
18036                    ? appearedChildPackages.size() : 0;
18037            for (int i = 0; i < packageCount; i++) {
18038                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18039                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18040                    true /*sendBootCompleted*/, false /*startReceiver*/,
18041                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18042            }
18043        }
18044
18045        private void sendSystemPackageUpdatedBroadcastsInternal() {
18046            Bundle extras = new Bundle(2);
18047            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18048            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18049            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18050                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18051            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18052                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18053            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18054                null, null, 0, removedPackage, null, null, null);
18055            if (installerPackageName != null) {
18056                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18057                        removedPackage, extras, 0 /*flags*/,
18058                        installerPackageName, null, null, null);
18059                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18060                        removedPackage, extras, 0 /*flags*/,
18061                        installerPackageName, null, null, null);
18062            }
18063        }
18064
18065        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18066            // Don't send static shared library removal broadcasts as these
18067            // libs are visible only the the apps that depend on them an one
18068            // cannot remove the library if it has a dependency.
18069            if (isStaticSharedLib) {
18070                return;
18071            }
18072            Bundle extras = new Bundle(2);
18073            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18074            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18075            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18076            if (isUpdate || isRemovedPackageSystemUpdate) {
18077                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18078            }
18079            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18080            if (removedPackage != null) {
18081                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18082                    removedPackage, extras, 0, null /*targetPackage*/, null,
18083                    broadcastUsers, instantUserIds);
18084                if (installerPackageName != null) {
18085                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18086                            removedPackage, extras, 0 /*flags*/,
18087                            installerPackageName, null, broadcastUsers, instantUserIds);
18088                }
18089                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18090                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18091                        removedPackage, extras,
18092                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18093                        null, null, broadcastUsers, instantUserIds);
18094                    packageSender.notifyPackageRemoved(removedPackage);
18095                }
18096            }
18097            if (removedAppId >= 0) {
18098                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18099                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18100                    null, null, broadcastUsers, instantUserIds);
18101            }
18102        }
18103
18104        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18105            removedUsers = userIds;
18106            if (removedUsers == null) {
18107                broadcastUsers = null;
18108                return;
18109            }
18110
18111            broadcastUsers = EMPTY_INT_ARRAY;
18112            instantUserIds = EMPTY_INT_ARRAY;
18113            for (int i = userIds.length - 1; i >= 0; --i) {
18114                final int userId = userIds[i];
18115                if (deletedPackageSetting.getInstantApp(userId)) {
18116                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18117                } else {
18118                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18119                }
18120            }
18121        }
18122    }
18123
18124    /*
18125     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18126     * flag is not set, the data directory is removed as well.
18127     * make sure this flag is set for partially installed apps. If not its meaningless to
18128     * delete a partially installed application.
18129     */
18130    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18131            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18132        String packageName = ps.name;
18133        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18134        // Retrieve object to delete permissions for shared user later on
18135        final PackageParser.Package deletedPkg;
18136        final PackageSetting deletedPs;
18137        // reader
18138        synchronized (mPackages) {
18139            deletedPkg = mPackages.get(packageName);
18140            deletedPs = mSettings.mPackages.get(packageName);
18141            if (outInfo != null) {
18142                outInfo.removedPackage = packageName;
18143                outInfo.installerPackageName = ps.installerPackageName;
18144                outInfo.isStaticSharedLib = deletedPkg != null
18145                        && deletedPkg.staticSharedLibName != null;
18146                outInfo.populateUsers(deletedPs == null ? null
18147                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18148            }
18149        }
18150
18151        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18152
18153        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18154            final PackageParser.Package resolvedPkg;
18155            if (deletedPkg != null) {
18156                resolvedPkg = deletedPkg;
18157            } else {
18158                // We don't have a parsed package when it lives on an ejected
18159                // adopted storage device, so fake something together
18160                resolvedPkg = new PackageParser.Package(ps.name);
18161                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18162            }
18163            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18164                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18165            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18166            if (outInfo != null) {
18167                outInfo.dataRemoved = true;
18168            }
18169            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18170        }
18171
18172        int removedAppId = -1;
18173
18174        // writer
18175        synchronized (mPackages) {
18176            boolean installedStateChanged = false;
18177            if (deletedPs != null) {
18178                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18179                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18180                    clearDefaultBrowserIfNeeded(packageName);
18181                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18182                    removedAppId = mSettings.removePackageLPw(packageName);
18183                    if (outInfo != null) {
18184                        outInfo.removedAppId = removedAppId;
18185                    }
18186                    mPermissionManager.updatePermissions(
18187                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18188                    if (deletedPs.sharedUser != null) {
18189                        // Remove permissions associated with package. Since runtime
18190                        // permissions are per user we have to kill the removed package
18191                        // or packages running under the shared user of the removed
18192                        // package if revoking the permissions requested only by the removed
18193                        // package is successful and this causes a change in gids.
18194                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18195                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18196                                    userId);
18197                            if (userIdToKill == UserHandle.USER_ALL
18198                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18199                                // If gids changed for this user, kill all affected packages.
18200                                mHandler.post(new Runnable() {
18201                                    @Override
18202                                    public void run() {
18203                                        // This has to happen with no lock held.
18204                                        killApplication(deletedPs.name, deletedPs.appId,
18205                                                KILL_APP_REASON_GIDS_CHANGED);
18206                                    }
18207                                });
18208                                break;
18209                            }
18210                        }
18211                    }
18212                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18213                }
18214                // make sure to preserve per-user disabled state if this removal was just
18215                // a downgrade of a system app to the factory package
18216                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18217                    if (DEBUG_REMOVE) {
18218                        Slog.d(TAG, "Propagating install state across downgrade");
18219                    }
18220                    for (int userId : allUserHandles) {
18221                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18222                        if (DEBUG_REMOVE) {
18223                            Slog.d(TAG, "    user " + userId + " => " + installed);
18224                        }
18225                        if (installed != ps.getInstalled(userId)) {
18226                            installedStateChanged = true;
18227                        }
18228                        ps.setInstalled(installed, userId);
18229                    }
18230                }
18231            }
18232            // can downgrade to reader
18233            if (writeSettings) {
18234                // Save settings now
18235                mSettings.writeLPr();
18236            }
18237            if (installedStateChanged) {
18238                mSettings.writeKernelMappingLPr(ps);
18239            }
18240        }
18241        if (removedAppId != -1) {
18242            // A user ID was deleted here. Go through all users and remove it
18243            // from KeyStore.
18244            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18245        }
18246    }
18247
18248    static boolean locationIsPrivileged(String path) {
18249        try {
18250            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18251            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18252            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18253            return path.startsWith(privilegedAppDir.getCanonicalPath())
18254                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18255                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18256        } catch (IOException e) {
18257            Slog.e(TAG, "Unable to access code path " + path);
18258        }
18259        return false;
18260    }
18261
18262    static boolean locationIsOem(String path) {
18263        try {
18264            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18265        } catch (IOException e) {
18266            Slog.e(TAG, "Unable to access code path " + path);
18267        }
18268        return false;
18269    }
18270
18271    static boolean locationIsVendor(String path) {
18272        try {
18273            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
18274        } catch (IOException e) {
18275            Slog.e(TAG, "Unable to access code path " + path);
18276        }
18277        return false;
18278    }
18279
18280    static boolean locationIsProduct(String path) {
18281        try {
18282            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18283        } catch (IOException e) {
18284            Slog.e(TAG, "Unable to access code path " + path);
18285        }
18286        return false;
18287    }
18288
18289    /*
18290     * Tries to delete system package.
18291     */
18292    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18293            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18294            boolean writeSettings) {
18295        if (deletedPs.parentPackageName != null) {
18296            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18297            return false;
18298        }
18299
18300        final boolean applyUserRestrictions
18301                = (allUserHandles != null) && (outInfo.origUsers != null);
18302        final PackageSetting disabledPs;
18303        // Confirm if the system package has been updated
18304        // An updated system app can be deleted. This will also have to restore
18305        // the system pkg from system partition
18306        // reader
18307        synchronized (mPackages) {
18308            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18309        }
18310
18311        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18312                + " disabledPs=" + disabledPs);
18313
18314        if (disabledPs == null) {
18315            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18316            return false;
18317        } else if (DEBUG_REMOVE) {
18318            Slog.d(TAG, "Deleting system pkg from data partition");
18319        }
18320
18321        if (DEBUG_REMOVE) {
18322            if (applyUserRestrictions) {
18323                Slog.d(TAG, "Remembering install states:");
18324                for (int userId : allUserHandles) {
18325                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18326                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18327                }
18328            }
18329        }
18330
18331        // Delete the updated package
18332        outInfo.isRemovedPackageSystemUpdate = true;
18333        if (outInfo.removedChildPackages != null) {
18334            final int childCount = (deletedPs.childPackageNames != null)
18335                    ? deletedPs.childPackageNames.size() : 0;
18336            for (int i = 0; i < childCount; i++) {
18337                String childPackageName = deletedPs.childPackageNames.get(i);
18338                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18339                        .contains(childPackageName)) {
18340                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18341                            childPackageName);
18342                    if (childInfo != null) {
18343                        childInfo.isRemovedPackageSystemUpdate = true;
18344                    }
18345                }
18346            }
18347        }
18348
18349        if (disabledPs.versionCode < deletedPs.versionCode) {
18350            // Delete data for downgrades
18351            flags &= ~PackageManager.DELETE_KEEP_DATA;
18352        } else {
18353            // Preserve data by setting flag
18354            flags |= PackageManager.DELETE_KEEP_DATA;
18355        }
18356
18357        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18358                outInfo, writeSettings, disabledPs.pkg);
18359        if (!ret) {
18360            return false;
18361        }
18362
18363        // writer
18364        synchronized (mPackages) {
18365            // NOTE: The system package always needs to be enabled; even if it's for
18366            // a compressed stub. If we don't, installing the system package fails
18367            // during scan [scanning checks the disabled packages]. We will reverse
18368            // this later, after we've "installed" the stub.
18369            // Reinstate the old system package
18370            enableSystemPackageLPw(disabledPs.pkg);
18371            // Remove any native libraries from the upgraded package.
18372            removeNativeBinariesLI(deletedPs);
18373        }
18374
18375        // Install the system package
18376        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18377        try {
18378            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18379                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18380        } catch (PackageManagerException e) {
18381            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18382                    + e.getMessage());
18383            return false;
18384        } finally {
18385            if (disabledPs.pkg.isStub) {
18386                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18387            }
18388        }
18389        return true;
18390    }
18391
18392    /**
18393     * Installs a package that's already on the system partition.
18394     */
18395    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18396            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18397            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18398                    throws PackageManagerException {
18399        @ParseFlags int parseFlags =
18400                mDefParseFlags
18401                | PackageParser.PARSE_MUST_BE_APK
18402                | PackageParser.PARSE_IS_SYSTEM_DIR;
18403        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18404        if (isPrivileged || locationIsPrivileged(codePathString)) {
18405            scanFlags |= SCAN_AS_PRIVILEGED;
18406        }
18407        if (locationIsOem(codePathString)) {
18408            scanFlags |= SCAN_AS_OEM;
18409        }
18410        if (locationIsVendor(codePathString)) {
18411            scanFlags |= SCAN_AS_VENDOR;
18412        }
18413        if (locationIsProduct(codePathString)) {
18414            scanFlags |= SCAN_AS_PRODUCT;
18415        }
18416
18417        final File codePath = new File(codePathString);
18418        final PackageParser.Package pkg =
18419                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18420
18421        try {
18422            // update shared libraries for the newly re-installed system package
18423            updateSharedLibrariesLPr(pkg, null);
18424        } catch (PackageManagerException e) {
18425            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18426        }
18427
18428        prepareAppDataAfterInstallLIF(pkg);
18429
18430        // writer
18431        synchronized (mPackages) {
18432            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18433
18434            // Propagate the permissions state as we do not want to drop on the floor
18435            // runtime permissions. The update permissions method below will take
18436            // care of removing obsolete permissions and grant install permissions.
18437            if (origPermissionState != null) {
18438                ps.getPermissionsState().copyFrom(origPermissionState);
18439            }
18440            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18441                    mPermissionCallback);
18442
18443            final boolean applyUserRestrictions
18444                    = (allUserHandles != null) && (origUserHandles != null);
18445            if (applyUserRestrictions) {
18446                boolean installedStateChanged = false;
18447                if (DEBUG_REMOVE) {
18448                    Slog.d(TAG, "Propagating install state across reinstall");
18449                }
18450                for (int userId : allUserHandles) {
18451                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18452                    if (DEBUG_REMOVE) {
18453                        Slog.d(TAG, "    user " + userId + " => " + installed);
18454                    }
18455                    if (installed != ps.getInstalled(userId)) {
18456                        installedStateChanged = true;
18457                    }
18458                    ps.setInstalled(installed, userId);
18459
18460                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18461                }
18462                // Regardless of writeSettings we need to ensure that this restriction
18463                // state propagation is persisted
18464                mSettings.writeAllUsersPackageRestrictionsLPr();
18465                if (installedStateChanged) {
18466                    mSettings.writeKernelMappingLPr(ps);
18467                }
18468            }
18469            // can downgrade to reader here
18470            if (writeSettings) {
18471                mSettings.writeLPr();
18472            }
18473        }
18474        return pkg;
18475    }
18476
18477    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18478            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18479            PackageRemovedInfo outInfo, boolean writeSettings,
18480            PackageParser.Package replacingPackage) {
18481        synchronized (mPackages) {
18482            if (outInfo != null) {
18483                outInfo.uid = ps.appId;
18484            }
18485
18486            if (outInfo != null && outInfo.removedChildPackages != null) {
18487                final int childCount = (ps.childPackageNames != null)
18488                        ? ps.childPackageNames.size() : 0;
18489                for (int i = 0; i < childCount; i++) {
18490                    String childPackageName = ps.childPackageNames.get(i);
18491                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18492                    if (childPs == null) {
18493                        return false;
18494                    }
18495                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18496                            childPackageName);
18497                    if (childInfo != null) {
18498                        childInfo.uid = childPs.appId;
18499                    }
18500                }
18501            }
18502        }
18503
18504        // Delete package data from internal structures and also remove data if flag is set
18505        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18506
18507        // Delete the child packages data
18508        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18509        for (int i = 0; i < childCount; i++) {
18510            PackageSetting childPs;
18511            synchronized (mPackages) {
18512                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18513            }
18514            if (childPs != null) {
18515                PackageRemovedInfo childOutInfo = (outInfo != null
18516                        && outInfo.removedChildPackages != null)
18517                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18518                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18519                        && (replacingPackage != null
18520                        && !replacingPackage.hasChildPackage(childPs.name))
18521                        ? flags & ~DELETE_KEEP_DATA : flags;
18522                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18523                        deleteFlags, writeSettings);
18524            }
18525        }
18526
18527        // Delete application code and resources only for parent packages
18528        if (ps.parentPackageName == null) {
18529            if (deleteCodeAndResources && (outInfo != null)) {
18530                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18531                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18532                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18533            }
18534        }
18535
18536        return true;
18537    }
18538
18539    @Override
18540    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18541            int userId) {
18542        mContext.enforceCallingOrSelfPermission(
18543                android.Manifest.permission.DELETE_PACKAGES, null);
18544        synchronized (mPackages) {
18545            // Cannot block uninstall of static shared libs as they are
18546            // considered a part of the using app (emulating static linking).
18547            // Also static libs are installed always on internal storage.
18548            PackageParser.Package pkg = mPackages.get(packageName);
18549            if (pkg != null && pkg.staticSharedLibName != null) {
18550                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18551                        + " providing static shared library: " + pkg.staticSharedLibName);
18552                return false;
18553            }
18554            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18555            mSettings.writePackageRestrictionsLPr(userId);
18556        }
18557        return true;
18558    }
18559
18560    @Override
18561    public boolean getBlockUninstallForUser(String packageName, int userId) {
18562        synchronized (mPackages) {
18563            final PackageSetting ps = mSettings.mPackages.get(packageName);
18564            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18565                return false;
18566            }
18567            return mSettings.getBlockUninstallLPr(userId, packageName);
18568        }
18569    }
18570
18571    @Override
18572    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18573        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18574        synchronized (mPackages) {
18575            PackageSetting ps = mSettings.mPackages.get(packageName);
18576            if (ps == null) {
18577                Log.w(TAG, "Package doesn't exist: " + packageName);
18578                return false;
18579            }
18580            if (systemUserApp) {
18581                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18582            } else {
18583                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18584            }
18585            mSettings.writeLPr();
18586        }
18587        return true;
18588    }
18589
18590    /*
18591     * This method handles package deletion in general
18592     */
18593    private boolean deletePackageLIF(String packageName, UserHandle user,
18594            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18595            PackageRemovedInfo outInfo, boolean writeSettings,
18596            PackageParser.Package replacingPackage) {
18597        if (packageName == null) {
18598            Slog.w(TAG, "Attempt to delete null packageName.");
18599            return false;
18600        }
18601
18602        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18603
18604        PackageSetting ps;
18605        synchronized (mPackages) {
18606            ps = mSettings.mPackages.get(packageName);
18607            if (ps == null) {
18608                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18609                return false;
18610            }
18611
18612            if (ps.parentPackageName != null && (!isSystemApp(ps)
18613                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18614                if (DEBUG_REMOVE) {
18615                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18616                            + ((user == null) ? UserHandle.USER_ALL : user));
18617                }
18618                final int removedUserId = (user != null) ? user.getIdentifier()
18619                        : UserHandle.USER_ALL;
18620                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18621                    return false;
18622                }
18623                markPackageUninstalledForUserLPw(ps, user);
18624                scheduleWritePackageRestrictionsLocked(user);
18625                return true;
18626            }
18627        }
18628
18629        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18630                && user.getIdentifier() != UserHandle.USER_ALL)) {
18631            // The caller is asking that the package only be deleted for a single
18632            // user.  To do this, we just mark its uninstalled state and delete
18633            // its data. If this is a system app, we only allow this to happen if
18634            // they have set the special DELETE_SYSTEM_APP which requests different
18635            // semantics than normal for uninstalling system apps.
18636            markPackageUninstalledForUserLPw(ps, user);
18637
18638            if (!isSystemApp(ps)) {
18639                // Do not uninstall the APK if an app should be cached
18640                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18641                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18642                    // Other user still have this package installed, so all
18643                    // we need to do is clear this user's data and save that
18644                    // it is uninstalled.
18645                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18646                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18647                        return false;
18648                    }
18649                    scheduleWritePackageRestrictionsLocked(user);
18650                    return true;
18651                } else {
18652                    // We need to set it back to 'installed' so the uninstall
18653                    // broadcasts will be sent correctly.
18654                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18655                    ps.setInstalled(true, user.getIdentifier());
18656                    mSettings.writeKernelMappingLPr(ps);
18657                }
18658            } else {
18659                // This is a system app, so we assume that the
18660                // other users still have this package installed, so all
18661                // we need to do is clear this user's data and save that
18662                // it is uninstalled.
18663                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18664                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18665                    return false;
18666                }
18667                scheduleWritePackageRestrictionsLocked(user);
18668                return true;
18669            }
18670        }
18671
18672        // If we are deleting a composite package for all users, keep track
18673        // of result for each child.
18674        if (ps.childPackageNames != null && outInfo != null) {
18675            synchronized (mPackages) {
18676                final int childCount = ps.childPackageNames.size();
18677                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18678                for (int i = 0; i < childCount; i++) {
18679                    String childPackageName = ps.childPackageNames.get(i);
18680                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18681                    childInfo.removedPackage = childPackageName;
18682                    childInfo.installerPackageName = ps.installerPackageName;
18683                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18684                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18685                    if (childPs != null) {
18686                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18687                    }
18688                }
18689            }
18690        }
18691
18692        boolean ret = false;
18693        if (isSystemApp(ps)) {
18694            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18695            // When an updated system application is deleted we delete the existing resources
18696            // as well and fall back to existing code in system partition
18697            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18698        } else {
18699            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18700            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18701                    outInfo, writeSettings, replacingPackage);
18702        }
18703
18704        // Take a note whether we deleted the package for all users
18705        if (outInfo != null) {
18706            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18707            if (outInfo.removedChildPackages != null) {
18708                synchronized (mPackages) {
18709                    final int childCount = outInfo.removedChildPackages.size();
18710                    for (int i = 0; i < childCount; i++) {
18711                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18712                        if (childInfo != null) {
18713                            childInfo.removedForAllUsers = mPackages.get(
18714                                    childInfo.removedPackage) == null;
18715                        }
18716                    }
18717                }
18718            }
18719            // If we uninstalled an update to a system app there may be some
18720            // child packages that appeared as they are declared in the system
18721            // app but were not declared in the update.
18722            if (isSystemApp(ps)) {
18723                synchronized (mPackages) {
18724                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18725                    final int childCount = (updatedPs.childPackageNames != null)
18726                            ? updatedPs.childPackageNames.size() : 0;
18727                    for (int i = 0; i < childCount; i++) {
18728                        String childPackageName = updatedPs.childPackageNames.get(i);
18729                        if (outInfo.removedChildPackages == null
18730                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18731                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18732                            if (childPs == null) {
18733                                continue;
18734                            }
18735                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18736                            installRes.name = childPackageName;
18737                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18738                            installRes.pkg = mPackages.get(childPackageName);
18739                            installRes.uid = childPs.pkg.applicationInfo.uid;
18740                            if (outInfo.appearedChildPackages == null) {
18741                                outInfo.appearedChildPackages = new ArrayMap<>();
18742                            }
18743                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18744                        }
18745                    }
18746                }
18747            }
18748        }
18749
18750        return ret;
18751    }
18752
18753    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18754        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18755                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18756        for (int nextUserId : userIds) {
18757            if (DEBUG_REMOVE) {
18758                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18759            }
18760            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18761                    false /*installed*/,
18762                    true /*stopped*/,
18763                    true /*notLaunched*/,
18764                    false /*hidden*/,
18765                    false /*suspended*/,
18766                    false /*instantApp*/,
18767                    false /*virtualPreload*/,
18768                    null /*lastDisableAppCaller*/,
18769                    null /*enabledComponents*/,
18770                    null /*disabledComponents*/,
18771                    ps.readUserState(nextUserId).domainVerificationStatus,
18772                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18773                    null /*harmfulAppWarning*/);
18774        }
18775        mSettings.writeKernelMappingLPr(ps);
18776    }
18777
18778    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18779            PackageRemovedInfo outInfo) {
18780        final PackageParser.Package pkg;
18781        synchronized (mPackages) {
18782            pkg = mPackages.get(ps.name);
18783        }
18784
18785        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18786                : new int[] {userId};
18787        for (int nextUserId : userIds) {
18788            if (DEBUG_REMOVE) {
18789                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18790                        + nextUserId);
18791            }
18792
18793            destroyAppDataLIF(pkg, userId,
18794                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18795            destroyAppProfilesLIF(pkg, userId);
18796            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18797            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18798            schedulePackageCleaning(ps.name, nextUserId, false);
18799            synchronized (mPackages) {
18800                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18801                    scheduleWritePackageRestrictionsLocked(nextUserId);
18802                }
18803                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18804            }
18805        }
18806
18807        if (outInfo != null) {
18808            outInfo.removedPackage = ps.name;
18809            outInfo.installerPackageName = ps.installerPackageName;
18810            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18811            outInfo.removedAppId = ps.appId;
18812            outInfo.removedUsers = userIds;
18813            outInfo.broadcastUsers = userIds;
18814        }
18815
18816        return true;
18817    }
18818
18819    private final class ClearStorageConnection implements ServiceConnection {
18820        IMediaContainerService mContainerService;
18821
18822        @Override
18823        public void onServiceConnected(ComponentName name, IBinder service) {
18824            synchronized (this) {
18825                mContainerService = IMediaContainerService.Stub
18826                        .asInterface(Binder.allowBlocking(service));
18827                notifyAll();
18828            }
18829        }
18830
18831        @Override
18832        public void onServiceDisconnected(ComponentName name) {
18833        }
18834    }
18835
18836    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18837        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18838
18839        final boolean mounted;
18840        if (Environment.isExternalStorageEmulated()) {
18841            mounted = true;
18842        } else {
18843            final String status = Environment.getExternalStorageState();
18844
18845            mounted = status.equals(Environment.MEDIA_MOUNTED)
18846                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18847        }
18848
18849        if (!mounted) {
18850            return;
18851        }
18852
18853        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18854        int[] users;
18855        if (userId == UserHandle.USER_ALL) {
18856            users = sUserManager.getUserIds();
18857        } else {
18858            users = new int[] { userId };
18859        }
18860        final ClearStorageConnection conn = new ClearStorageConnection();
18861        if (mContext.bindServiceAsUser(
18862                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18863            try {
18864                for (int curUser : users) {
18865                    long timeout = SystemClock.uptimeMillis() + 5000;
18866                    synchronized (conn) {
18867                        long now;
18868                        while (conn.mContainerService == null &&
18869                                (now = SystemClock.uptimeMillis()) < timeout) {
18870                            try {
18871                                conn.wait(timeout - now);
18872                            } catch (InterruptedException e) {
18873                            }
18874                        }
18875                    }
18876                    if (conn.mContainerService == null) {
18877                        return;
18878                    }
18879
18880                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18881                    clearDirectory(conn.mContainerService,
18882                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18883                    if (allData) {
18884                        clearDirectory(conn.mContainerService,
18885                                userEnv.buildExternalStorageAppDataDirs(packageName));
18886                        clearDirectory(conn.mContainerService,
18887                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18888                    }
18889                }
18890            } finally {
18891                mContext.unbindService(conn);
18892            }
18893        }
18894    }
18895
18896    @Override
18897    public void clearApplicationProfileData(String packageName) {
18898        enforceSystemOrRoot("Only the system can clear all profile data");
18899
18900        final PackageParser.Package pkg;
18901        synchronized (mPackages) {
18902            pkg = mPackages.get(packageName);
18903        }
18904
18905        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18906            synchronized (mInstallLock) {
18907                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18908            }
18909        }
18910    }
18911
18912    @Override
18913    public void clearApplicationUserData(final String packageName,
18914            final IPackageDataObserver observer, final int userId) {
18915        mContext.enforceCallingOrSelfPermission(
18916                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18917
18918        final int callingUid = Binder.getCallingUid();
18919        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18920                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18921
18922        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18923        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18924        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18925            throw new SecurityException("Cannot clear data for a protected package: "
18926                    + packageName);
18927        }
18928        // Queue up an async operation since the package deletion may take a little while.
18929        mHandler.post(new Runnable() {
18930            public void run() {
18931                mHandler.removeCallbacks(this);
18932                final boolean succeeded;
18933                if (!filterApp) {
18934                    try (PackageFreezer freezer = freezePackage(packageName,
18935                            "clearApplicationUserData")) {
18936                        synchronized (mInstallLock) {
18937                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18938                        }
18939                        clearExternalStorageDataSync(packageName, userId, true);
18940                        synchronized (mPackages) {
18941                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18942                                    packageName, userId);
18943                        }
18944                    }
18945                    if (succeeded) {
18946                        // invoke DeviceStorageMonitor's update method to clear any notifications
18947                        DeviceStorageMonitorInternal dsm = LocalServices
18948                                .getService(DeviceStorageMonitorInternal.class);
18949                        if (dsm != null) {
18950                            dsm.checkMemory();
18951                        }
18952                    }
18953                } else {
18954                    succeeded = false;
18955                }
18956                if (observer != null) {
18957                    try {
18958                        observer.onRemoveCompleted(packageName, succeeded);
18959                    } catch (RemoteException e) {
18960                        Log.i(TAG, "Observer no longer exists.");
18961                    }
18962                } //end if observer
18963            } //end run
18964        });
18965    }
18966
18967    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18968        if (packageName == null) {
18969            Slog.w(TAG, "Attempt to delete null packageName.");
18970            return false;
18971        }
18972
18973        // Try finding details about the requested package
18974        PackageParser.Package pkg;
18975        synchronized (mPackages) {
18976            pkg = mPackages.get(packageName);
18977            if (pkg == null) {
18978                final PackageSetting ps = mSettings.mPackages.get(packageName);
18979                if (ps != null) {
18980                    pkg = ps.pkg;
18981                }
18982            }
18983
18984            if (pkg == null) {
18985                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18986                return false;
18987            }
18988
18989            PackageSetting ps = (PackageSetting) pkg.mExtras;
18990            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18991        }
18992
18993        clearAppDataLIF(pkg, userId,
18994                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18995
18996        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18997        removeKeystoreDataIfNeeded(userId, appId);
18998
18999        UserManagerInternal umInternal = getUserManagerInternal();
19000        final int flags;
19001        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19002            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19003        } else if (umInternal.isUserRunning(userId)) {
19004            flags = StorageManager.FLAG_STORAGE_DE;
19005        } else {
19006            flags = 0;
19007        }
19008        prepareAppDataContentsLIF(pkg, userId, flags);
19009
19010        return true;
19011    }
19012
19013    /**
19014     * Reverts user permission state changes (permissions and flags) in
19015     * all packages for a given user.
19016     *
19017     * @param userId The device user for which to do a reset.
19018     */
19019    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19020        final int packageCount = mPackages.size();
19021        for (int i = 0; i < packageCount; i++) {
19022            PackageParser.Package pkg = mPackages.valueAt(i);
19023            PackageSetting ps = (PackageSetting) pkg.mExtras;
19024            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19025        }
19026    }
19027
19028    private void resetNetworkPolicies(int userId) {
19029        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19030    }
19031
19032    /**
19033     * Reverts user permission state changes (permissions and flags).
19034     *
19035     * @param ps The package for which to reset.
19036     * @param userId The device user for which to do a reset.
19037     */
19038    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19039            final PackageSetting ps, final int userId) {
19040        if (ps.pkg == null) {
19041            return;
19042        }
19043
19044        // These are flags that can change base on user actions.
19045        final int userSettableMask = FLAG_PERMISSION_USER_SET
19046                | FLAG_PERMISSION_USER_FIXED
19047                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19048                | FLAG_PERMISSION_REVIEW_REQUIRED;
19049
19050        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19051                | FLAG_PERMISSION_POLICY_FIXED;
19052
19053        boolean writeInstallPermissions = false;
19054        boolean writeRuntimePermissions = false;
19055
19056        final int permissionCount = ps.pkg.requestedPermissions.size();
19057        for (int i = 0; i < permissionCount; i++) {
19058            final String permName = ps.pkg.requestedPermissions.get(i);
19059            final BasePermission bp =
19060                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19061            if (bp == null) {
19062                continue;
19063            }
19064
19065            // If shared user we just reset the state to which only this app contributed.
19066            if (ps.sharedUser != null) {
19067                boolean used = false;
19068                final int packageCount = ps.sharedUser.packages.size();
19069                for (int j = 0; j < packageCount; j++) {
19070                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19071                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19072                            && pkg.pkg.requestedPermissions.contains(permName)) {
19073                        used = true;
19074                        break;
19075                    }
19076                }
19077                if (used) {
19078                    continue;
19079                }
19080            }
19081
19082            final PermissionsState permissionsState = ps.getPermissionsState();
19083
19084            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19085
19086            // Always clear the user settable flags.
19087            final boolean hasInstallState =
19088                    permissionsState.getInstallPermissionState(permName) != null;
19089            // If permission review is enabled and this is a legacy app, mark the
19090            // permission as requiring a review as this is the initial state.
19091            int flags = 0;
19092            if (mSettings.mPermissions.mPermissionReviewRequired
19093                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19094                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19095            }
19096            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19097                if (hasInstallState) {
19098                    writeInstallPermissions = true;
19099                } else {
19100                    writeRuntimePermissions = true;
19101                }
19102            }
19103
19104            // Below is only runtime permission handling.
19105            if (!bp.isRuntime()) {
19106                continue;
19107            }
19108
19109            // Never clobber system or policy.
19110            if ((oldFlags & policyOrSystemFlags) != 0) {
19111                continue;
19112            }
19113
19114            // If this permission was granted by default, make sure it is.
19115            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19116                if (permissionsState.grantRuntimePermission(bp, userId)
19117                        != PERMISSION_OPERATION_FAILURE) {
19118                    writeRuntimePermissions = true;
19119                }
19120            // If permission review is enabled the permissions for a legacy apps
19121            // are represented as constantly granted runtime ones, so don't revoke.
19122            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19123                // Otherwise, reset the permission.
19124                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19125                switch (revokeResult) {
19126                    case PERMISSION_OPERATION_SUCCESS:
19127                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19128                        writeRuntimePermissions = true;
19129                        final int appId = ps.appId;
19130                        mHandler.post(new Runnable() {
19131                            @Override
19132                            public void run() {
19133                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19134                            }
19135                        });
19136                    } break;
19137                }
19138            }
19139        }
19140
19141        // Synchronously write as we are taking permissions away.
19142        if (writeRuntimePermissions) {
19143            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19144        }
19145
19146        // Synchronously write as we are taking permissions away.
19147        if (writeInstallPermissions) {
19148            mSettings.writeLPr();
19149        }
19150    }
19151
19152    /**
19153     * Remove entries from the keystore daemon. Will only remove it if the
19154     * {@code appId} is valid.
19155     */
19156    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19157        if (appId < 0) {
19158            return;
19159        }
19160
19161        final KeyStore keyStore = KeyStore.getInstance();
19162        if (keyStore != null) {
19163            if (userId == UserHandle.USER_ALL) {
19164                for (final int individual : sUserManager.getUserIds()) {
19165                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19166                }
19167            } else {
19168                keyStore.clearUid(UserHandle.getUid(userId, appId));
19169            }
19170        } else {
19171            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19172        }
19173    }
19174
19175    @Override
19176    public void deleteApplicationCacheFiles(final String packageName,
19177            final IPackageDataObserver observer) {
19178        final int userId = UserHandle.getCallingUserId();
19179        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19180    }
19181
19182    @Override
19183    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19184            final IPackageDataObserver observer) {
19185        final int callingUid = Binder.getCallingUid();
19186        mContext.enforceCallingOrSelfPermission(
19187                android.Manifest.permission.DELETE_CACHE_FILES, null);
19188        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19189                /* requireFullPermission= */ true, /* checkShell= */ false,
19190                "delete application cache files");
19191        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19192                android.Manifest.permission.ACCESS_INSTANT_APPS);
19193
19194        final PackageParser.Package pkg;
19195        synchronized (mPackages) {
19196            pkg = mPackages.get(packageName);
19197        }
19198
19199        // Queue up an async operation since the package deletion may take a little while.
19200        mHandler.post(new Runnable() {
19201            public void run() {
19202                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19203                boolean doClearData = true;
19204                if (ps != null) {
19205                    final boolean targetIsInstantApp =
19206                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19207                    doClearData = !targetIsInstantApp
19208                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19209                }
19210                if (doClearData) {
19211                    synchronized (mInstallLock) {
19212                        final int flags = StorageManager.FLAG_STORAGE_DE
19213                                | StorageManager.FLAG_STORAGE_CE;
19214                        // We're only clearing cache files, so we don't care if the
19215                        // app is unfrozen and still able to run
19216                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19217                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19218                    }
19219                    clearExternalStorageDataSync(packageName, userId, false);
19220                }
19221                if (observer != null) {
19222                    try {
19223                        observer.onRemoveCompleted(packageName, true);
19224                    } catch (RemoteException e) {
19225                        Log.i(TAG, "Observer no longer exists.");
19226                    }
19227                }
19228            }
19229        });
19230    }
19231
19232    @Override
19233    public void getPackageSizeInfo(final String packageName, int userHandle,
19234            final IPackageStatsObserver observer) {
19235        throw new UnsupportedOperationException(
19236                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19237    }
19238
19239    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19240        final PackageSetting ps;
19241        synchronized (mPackages) {
19242            ps = mSettings.mPackages.get(packageName);
19243            if (ps == null) {
19244                Slog.w(TAG, "Failed to find settings for " + packageName);
19245                return false;
19246            }
19247        }
19248
19249        final String[] packageNames = { packageName };
19250        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19251        final String[] codePaths = { ps.codePathString };
19252
19253        try {
19254            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19255                    ps.appId, ceDataInodes, codePaths, stats);
19256
19257            // For now, ignore code size of packages on system partition
19258            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19259                stats.codeSize = 0;
19260            }
19261
19262            // External clients expect these to be tracked separately
19263            stats.dataSize -= stats.cacheSize;
19264
19265        } catch (InstallerException e) {
19266            Slog.w(TAG, String.valueOf(e));
19267            return false;
19268        }
19269
19270        return true;
19271    }
19272
19273    private int getUidTargetSdkVersionLockedLPr(int uid) {
19274        Object obj = mSettings.getUserIdLPr(uid);
19275        if (obj instanceof SharedUserSetting) {
19276            final SharedUserSetting sus = (SharedUserSetting) obj;
19277            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19278            final Iterator<PackageSetting> it = sus.packages.iterator();
19279            while (it.hasNext()) {
19280                final PackageSetting ps = it.next();
19281                if (ps.pkg != null) {
19282                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19283                    if (v < vers) vers = v;
19284                }
19285            }
19286            return vers;
19287        } else if (obj instanceof PackageSetting) {
19288            final PackageSetting ps = (PackageSetting) obj;
19289            if (ps.pkg != null) {
19290                return ps.pkg.applicationInfo.targetSdkVersion;
19291            }
19292        }
19293        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19294    }
19295
19296    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19297        final PackageParser.Package p = mPackages.get(packageName);
19298        if (p != null) {
19299            return p.applicationInfo.targetSdkVersion;
19300        }
19301        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19302    }
19303
19304    @Override
19305    public void addPreferredActivity(IntentFilter filter, int match,
19306            ComponentName[] set, ComponentName activity, int userId) {
19307        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19308                "Adding preferred");
19309    }
19310
19311    private void addPreferredActivityInternal(IntentFilter filter, int match,
19312            ComponentName[] set, ComponentName activity, boolean always, int userId,
19313            String opname) {
19314        // writer
19315        int callingUid = Binder.getCallingUid();
19316        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19317                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19318        if (filter.countActions() == 0) {
19319            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19320            return;
19321        }
19322        synchronized (mPackages) {
19323            if (mContext.checkCallingOrSelfPermission(
19324                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19325                    != PackageManager.PERMISSION_GRANTED) {
19326                if (getUidTargetSdkVersionLockedLPr(callingUid)
19327                        < Build.VERSION_CODES.FROYO) {
19328                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19329                            + callingUid);
19330                    return;
19331                }
19332                mContext.enforceCallingOrSelfPermission(
19333                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19334            }
19335
19336            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19337            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19338                    + userId + ":");
19339            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19340            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19341            scheduleWritePackageRestrictionsLocked(userId);
19342            postPreferredActivityChangedBroadcast(userId);
19343        }
19344    }
19345
19346    private void postPreferredActivityChangedBroadcast(int userId) {
19347        mHandler.post(() -> {
19348            final IActivityManager am = ActivityManager.getService();
19349            if (am == null) {
19350                return;
19351            }
19352
19353            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19354            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19355            try {
19356                am.broadcastIntent(null, intent, null, null,
19357                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19358                        null, false, false, userId);
19359            } catch (RemoteException e) {
19360            }
19361        });
19362    }
19363
19364    @Override
19365    public void replacePreferredActivity(IntentFilter filter, int match,
19366            ComponentName[] set, ComponentName activity, int userId) {
19367        if (filter.countActions() != 1) {
19368            throw new IllegalArgumentException(
19369                    "replacePreferredActivity expects filter to have only 1 action.");
19370        }
19371        if (filter.countDataAuthorities() != 0
19372                || filter.countDataPaths() != 0
19373                || filter.countDataSchemes() > 1
19374                || filter.countDataTypes() != 0) {
19375            throw new IllegalArgumentException(
19376                    "replacePreferredActivity expects filter to have no data authorities, " +
19377                    "paths, or types; and at most one scheme.");
19378        }
19379
19380        final int callingUid = Binder.getCallingUid();
19381        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19382                true /* requireFullPermission */, false /* checkShell */,
19383                "replace preferred activity");
19384        synchronized (mPackages) {
19385            if (mContext.checkCallingOrSelfPermission(
19386                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19387                    != PackageManager.PERMISSION_GRANTED) {
19388                if (getUidTargetSdkVersionLockedLPr(callingUid)
19389                        < Build.VERSION_CODES.FROYO) {
19390                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19391                            + Binder.getCallingUid());
19392                    return;
19393                }
19394                mContext.enforceCallingOrSelfPermission(
19395                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19396            }
19397
19398            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19399            if (pir != null) {
19400                // Get all of the existing entries that exactly match this filter.
19401                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19402                if (existing != null && existing.size() == 1) {
19403                    PreferredActivity cur = existing.get(0);
19404                    if (DEBUG_PREFERRED) {
19405                        Slog.i(TAG, "Checking replace of preferred:");
19406                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19407                        if (!cur.mPref.mAlways) {
19408                            Slog.i(TAG, "  -- CUR; not mAlways!");
19409                        } else {
19410                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19411                            Slog.i(TAG, "  -- CUR: mSet="
19412                                    + Arrays.toString(cur.mPref.mSetComponents));
19413                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19414                            Slog.i(TAG, "  -- NEW: mMatch="
19415                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19416                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19417                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19418                        }
19419                    }
19420                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19421                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19422                            && cur.mPref.sameSet(set)) {
19423                        // Setting the preferred activity to what it happens to be already
19424                        if (DEBUG_PREFERRED) {
19425                            Slog.i(TAG, "Replacing with same preferred activity "
19426                                    + cur.mPref.mShortComponent + " for user "
19427                                    + userId + ":");
19428                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19429                        }
19430                        return;
19431                    }
19432                }
19433
19434                if (existing != null) {
19435                    if (DEBUG_PREFERRED) {
19436                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19437                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19438                    }
19439                    for (int i = 0; i < existing.size(); i++) {
19440                        PreferredActivity pa = existing.get(i);
19441                        if (DEBUG_PREFERRED) {
19442                            Slog.i(TAG, "Removing existing preferred activity "
19443                                    + pa.mPref.mComponent + ":");
19444                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19445                        }
19446                        pir.removeFilter(pa);
19447                    }
19448                }
19449            }
19450            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19451                    "Replacing preferred");
19452        }
19453    }
19454
19455    @Override
19456    public void clearPackagePreferredActivities(String packageName) {
19457        final int callingUid = Binder.getCallingUid();
19458        if (getInstantAppPackageName(callingUid) != null) {
19459            return;
19460        }
19461        // writer
19462        synchronized (mPackages) {
19463            PackageParser.Package pkg = mPackages.get(packageName);
19464            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19465                if (mContext.checkCallingOrSelfPermission(
19466                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19467                        != PackageManager.PERMISSION_GRANTED) {
19468                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19469                            < Build.VERSION_CODES.FROYO) {
19470                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19471                                + callingUid);
19472                        return;
19473                    }
19474                    mContext.enforceCallingOrSelfPermission(
19475                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19476                }
19477            }
19478            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19479            if (ps != null
19480                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19481                return;
19482            }
19483            int user = UserHandle.getCallingUserId();
19484            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19485                scheduleWritePackageRestrictionsLocked(user);
19486            }
19487        }
19488    }
19489
19490    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19491    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19492        ArrayList<PreferredActivity> removed = null;
19493        boolean changed = false;
19494        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19495            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19496            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19497            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19498                continue;
19499            }
19500            Iterator<PreferredActivity> it = pir.filterIterator();
19501            while (it.hasNext()) {
19502                PreferredActivity pa = it.next();
19503                // Mark entry for removal only if it matches the package name
19504                // and the entry is of type "always".
19505                if (packageName == null ||
19506                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19507                                && pa.mPref.mAlways)) {
19508                    if (removed == null) {
19509                        removed = new ArrayList<PreferredActivity>();
19510                    }
19511                    removed.add(pa);
19512                }
19513            }
19514            if (removed != null) {
19515                for (int j=0; j<removed.size(); j++) {
19516                    PreferredActivity pa = removed.get(j);
19517                    pir.removeFilter(pa);
19518                }
19519                changed = true;
19520            }
19521        }
19522        if (changed) {
19523            postPreferredActivityChangedBroadcast(userId);
19524        }
19525        return changed;
19526    }
19527
19528    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19529    private void clearIntentFilterVerificationsLPw(int userId) {
19530        final int packageCount = mPackages.size();
19531        for (int i = 0; i < packageCount; i++) {
19532            PackageParser.Package pkg = mPackages.valueAt(i);
19533            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19534        }
19535    }
19536
19537    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19538    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19539        if (userId == UserHandle.USER_ALL) {
19540            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19541                    sUserManager.getUserIds())) {
19542                for (int oneUserId : sUserManager.getUserIds()) {
19543                    scheduleWritePackageRestrictionsLocked(oneUserId);
19544                }
19545            }
19546        } else {
19547            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19548                scheduleWritePackageRestrictionsLocked(userId);
19549            }
19550        }
19551    }
19552
19553    /** Clears state for all users, and touches intent filter verification policy */
19554    void clearDefaultBrowserIfNeeded(String packageName) {
19555        for (int oneUserId : sUserManager.getUserIds()) {
19556            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19557        }
19558    }
19559
19560    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19561        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19562        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19563            if (packageName.equals(defaultBrowserPackageName)) {
19564                setDefaultBrowserPackageName(null, userId);
19565            }
19566        }
19567    }
19568
19569    @Override
19570    public void resetApplicationPreferences(int userId) {
19571        mContext.enforceCallingOrSelfPermission(
19572                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19573        final long identity = Binder.clearCallingIdentity();
19574        // writer
19575        try {
19576            synchronized (mPackages) {
19577                clearPackagePreferredActivitiesLPw(null, userId);
19578                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19579                // TODO: We have to reset the default SMS and Phone. This requires
19580                // significant refactoring to keep all default apps in the package
19581                // manager (cleaner but more work) or have the services provide
19582                // callbacks to the package manager to request a default app reset.
19583                applyFactoryDefaultBrowserLPw(userId);
19584                clearIntentFilterVerificationsLPw(userId);
19585                primeDomainVerificationsLPw(userId);
19586                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19587                scheduleWritePackageRestrictionsLocked(userId);
19588            }
19589            resetNetworkPolicies(userId);
19590        } finally {
19591            Binder.restoreCallingIdentity(identity);
19592        }
19593    }
19594
19595    @Override
19596    public int getPreferredActivities(List<IntentFilter> outFilters,
19597            List<ComponentName> outActivities, String packageName) {
19598        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19599            return 0;
19600        }
19601        int num = 0;
19602        final int userId = UserHandle.getCallingUserId();
19603        // reader
19604        synchronized (mPackages) {
19605            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19606            if (pir != null) {
19607                final Iterator<PreferredActivity> it = pir.filterIterator();
19608                while (it.hasNext()) {
19609                    final PreferredActivity pa = it.next();
19610                    if (packageName == null
19611                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19612                                    && pa.mPref.mAlways)) {
19613                        if (outFilters != null) {
19614                            outFilters.add(new IntentFilter(pa));
19615                        }
19616                        if (outActivities != null) {
19617                            outActivities.add(pa.mPref.mComponent);
19618                        }
19619                    }
19620                }
19621            }
19622        }
19623
19624        return num;
19625    }
19626
19627    @Override
19628    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19629            int userId) {
19630        int callingUid = Binder.getCallingUid();
19631        if (callingUid != Process.SYSTEM_UID) {
19632            throw new SecurityException(
19633                    "addPersistentPreferredActivity can only be run by the system");
19634        }
19635        if (filter.countActions() == 0) {
19636            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19637            return;
19638        }
19639        synchronized (mPackages) {
19640            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19641                    ":");
19642            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19643            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19644                    new PersistentPreferredActivity(filter, activity));
19645            scheduleWritePackageRestrictionsLocked(userId);
19646            postPreferredActivityChangedBroadcast(userId);
19647        }
19648    }
19649
19650    @Override
19651    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19652        int callingUid = Binder.getCallingUid();
19653        if (callingUid != Process.SYSTEM_UID) {
19654            throw new SecurityException(
19655                    "clearPackagePersistentPreferredActivities can only be run by the system");
19656        }
19657        ArrayList<PersistentPreferredActivity> removed = null;
19658        boolean changed = false;
19659        synchronized (mPackages) {
19660            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19661                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19662                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19663                        .valueAt(i);
19664                if (userId != thisUserId) {
19665                    continue;
19666                }
19667                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19668                while (it.hasNext()) {
19669                    PersistentPreferredActivity ppa = it.next();
19670                    // Mark entry for removal only if it matches the package name.
19671                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19672                        if (removed == null) {
19673                            removed = new ArrayList<PersistentPreferredActivity>();
19674                        }
19675                        removed.add(ppa);
19676                    }
19677                }
19678                if (removed != null) {
19679                    for (int j=0; j<removed.size(); j++) {
19680                        PersistentPreferredActivity ppa = removed.get(j);
19681                        ppir.removeFilter(ppa);
19682                    }
19683                    changed = true;
19684                }
19685            }
19686
19687            if (changed) {
19688                scheduleWritePackageRestrictionsLocked(userId);
19689                postPreferredActivityChangedBroadcast(userId);
19690            }
19691        }
19692    }
19693
19694    /**
19695     * Common machinery for picking apart a restored XML blob and passing
19696     * it to a caller-supplied functor to be applied to the running system.
19697     */
19698    private void restoreFromXml(XmlPullParser parser, int userId,
19699            String expectedStartTag, BlobXmlRestorer functor)
19700            throws IOException, XmlPullParserException {
19701        int type;
19702        while ((type = parser.next()) != XmlPullParser.START_TAG
19703                && type != XmlPullParser.END_DOCUMENT) {
19704        }
19705        if (type != XmlPullParser.START_TAG) {
19706            // oops didn't find a start tag?!
19707            if (DEBUG_BACKUP) {
19708                Slog.e(TAG, "Didn't find start tag during restore");
19709            }
19710            return;
19711        }
19712Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19713        // this is supposed to be TAG_PREFERRED_BACKUP
19714        if (!expectedStartTag.equals(parser.getName())) {
19715            if (DEBUG_BACKUP) {
19716                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19717            }
19718            return;
19719        }
19720
19721        // skip interfering stuff, then we're aligned with the backing implementation
19722        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19723Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19724        functor.apply(parser, userId);
19725    }
19726
19727    private interface BlobXmlRestorer {
19728        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19729    }
19730
19731    /**
19732     * Non-Binder method, support for the backup/restore mechanism: write the
19733     * full set of preferred activities in its canonical XML format.  Returns the
19734     * XML output as a byte array, or null if there is none.
19735     */
19736    @Override
19737    public byte[] getPreferredActivityBackup(int userId) {
19738        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19739            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19740        }
19741
19742        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19743        try {
19744            final XmlSerializer serializer = new FastXmlSerializer();
19745            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19746            serializer.startDocument(null, true);
19747            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19748
19749            synchronized (mPackages) {
19750                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19751            }
19752
19753            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19754            serializer.endDocument();
19755            serializer.flush();
19756        } catch (Exception e) {
19757            if (DEBUG_BACKUP) {
19758                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19759            }
19760            return null;
19761        }
19762
19763        return dataStream.toByteArray();
19764    }
19765
19766    @Override
19767    public void restorePreferredActivities(byte[] backup, int userId) {
19768        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19769            throw new SecurityException("Only the system may call restorePreferredActivities()");
19770        }
19771
19772        try {
19773            final XmlPullParser parser = Xml.newPullParser();
19774            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19775            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19776                    new BlobXmlRestorer() {
19777                        @Override
19778                        public void apply(XmlPullParser parser, int userId)
19779                                throws XmlPullParserException, IOException {
19780                            synchronized (mPackages) {
19781                                mSettings.readPreferredActivitiesLPw(parser, userId);
19782                            }
19783                        }
19784                    } );
19785        } catch (Exception e) {
19786            if (DEBUG_BACKUP) {
19787                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19788            }
19789        }
19790    }
19791
19792    /**
19793     * Non-Binder method, support for the backup/restore mechanism: write the
19794     * default browser (etc) settings in its canonical XML format.  Returns the default
19795     * browser XML representation as a byte array, or null if there is none.
19796     */
19797    @Override
19798    public byte[] getDefaultAppsBackup(int userId) {
19799        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19800            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19801        }
19802
19803        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19804        try {
19805            final XmlSerializer serializer = new FastXmlSerializer();
19806            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19807            serializer.startDocument(null, true);
19808            serializer.startTag(null, TAG_DEFAULT_APPS);
19809
19810            synchronized (mPackages) {
19811                mSettings.writeDefaultAppsLPr(serializer, userId);
19812            }
19813
19814            serializer.endTag(null, TAG_DEFAULT_APPS);
19815            serializer.endDocument();
19816            serializer.flush();
19817        } catch (Exception e) {
19818            if (DEBUG_BACKUP) {
19819                Slog.e(TAG, "Unable to write default apps for backup", e);
19820            }
19821            return null;
19822        }
19823
19824        return dataStream.toByteArray();
19825    }
19826
19827    @Override
19828    public void restoreDefaultApps(byte[] backup, int userId) {
19829        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19830            throw new SecurityException("Only the system may call restoreDefaultApps()");
19831        }
19832
19833        try {
19834            final XmlPullParser parser = Xml.newPullParser();
19835            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19836            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19837                    new BlobXmlRestorer() {
19838                        @Override
19839                        public void apply(XmlPullParser parser, int userId)
19840                                throws XmlPullParserException, IOException {
19841                            synchronized (mPackages) {
19842                                mSettings.readDefaultAppsLPw(parser, userId);
19843                            }
19844                        }
19845                    } );
19846        } catch (Exception e) {
19847            if (DEBUG_BACKUP) {
19848                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19849            }
19850        }
19851    }
19852
19853    @Override
19854    public byte[] getIntentFilterVerificationBackup(int userId) {
19855        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19856            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19857        }
19858
19859        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19860        try {
19861            final XmlSerializer serializer = new FastXmlSerializer();
19862            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19863            serializer.startDocument(null, true);
19864            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19865
19866            synchronized (mPackages) {
19867                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19868            }
19869
19870            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19871            serializer.endDocument();
19872            serializer.flush();
19873        } catch (Exception e) {
19874            if (DEBUG_BACKUP) {
19875                Slog.e(TAG, "Unable to write default apps for backup", e);
19876            }
19877            return null;
19878        }
19879
19880        return dataStream.toByteArray();
19881    }
19882
19883    @Override
19884    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19885        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19886            throw new SecurityException("Only the system may call restorePreferredActivities()");
19887        }
19888
19889        try {
19890            final XmlPullParser parser = Xml.newPullParser();
19891            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19892            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19893                    new BlobXmlRestorer() {
19894                        @Override
19895                        public void apply(XmlPullParser parser, int userId)
19896                                throws XmlPullParserException, IOException {
19897                            synchronized (mPackages) {
19898                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19899                                mSettings.writeLPr();
19900                            }
19901                        }
19902                    } );
19903        } catch (Exception e) {
19904            if (DEBUG_BACKUP) {
19905                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19906            }
19907        }
19908    }
19909
19910    @Override
19911    public byte[] getPermissionGrantBackup(int userId) {
19912        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19913            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19914        }
19915
19916        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19917        try {
19918            final XmlSerializer serializer = new FastXmlSerializer();
19919            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19920            serializer.startDocument(null, true);
19921            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19922
19923            synchronized (mPackages) {
19924                serializeRuntimePermissionGrantsLPr(serializer, userId);
19925            }
19926
19927            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19928            serializer.endDocument();
19929            serializer.flush();
19930        } catch (Exception e) {
19931            if (DEBUG_BACKUP) {
19932                Slog.e(TAG, "Unable to write default apps for backup", e);
19933            }
19934            return null;
19935        }
19936
19937        return dataStream.toByteArray();
19938    }
19939
19940    @Override
19941    public void restorePermissionGrants(byte[] backup, int userId) {
19942        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19943            throw new SecurityException("Only the system may call restorePermissionGrants()");
19944        }
19945
19946        try {
19947            final XmlPullParser parser = Xml.newPullParser();
19948            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19949            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19950                    new BlobXmlRestorer() {
19951                        @Override
19952                        public void apply(XmlPullParser parser, int userId)
19953                                throws XmlPullParserException, IOException {
19954                            synchronized (mPackages) {
19955                                processRestoredPermissionGrantsLPr(parser, userId);
19956                            }
19957                        }
19958                    } );
19959        } catch (Exception e) {
19960            if (DEBUG_BACKUP) {
19961                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19962            }
19963        }
19964    }
19965
19966    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19967            throws IOException {
19968        serializer.startTag(null, TAG_ALL_GRANTS);
19969
19970        final int N = mSettings.mPackages.size();
19971        for (int i = 0; i < N; i++) {
19972            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19973            boolean pkgGrantsKnown = false;
19974
19975            PermissionsState packagePerms = ps.getPermissionsState();
19976
19977            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19978                final int grantFlags = state.getFlags();
19979                // only look at grants that are not system/policy fixed
19980                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19981                    final boolean isGranted = state.isGranted();
19982                    // And only back up the user-twiddled state bits
19983                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19984                        final String packageName = mSettings.mPackages.keyAt(i);
19985                        if (!pkgGrantsKnown) {
19986                            serializer.startTag(null, TAG_GRANT);
19987                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19988                            pkgGrantsKnown = true;
19989                        }
19990
19991                        final boolean userSet =
19992                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19993                        final boolean userFixed =
19994                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19995                        final boolean revoke =
19996                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19997
19998                        serializer.startTag(null, TAG_PERMISSION);
19999                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20000                        if (isGranted) {
20001                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20002                        }
20003                        if (userSet) {
20004                            serializer.attribute(null, ATTR_USER_SET, "true");
20005                        }
20006                        if (userFixed) {
20007                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20008                        }
20009                        if (revoke) {
20010                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20011                        }
20012                        serializer.endTag(null, TAG_PERMISSION);
20013                    }
20014                }
20015            }
20016
20017            if (pkgGrantsKnown) {
20018                serializer.endTag(null, TAG_GRANT);
20019            }
20020        }
20021
20022        serializer.endTag(null, TAG_ALL_GRANTS);
20023    }
20024
20025    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20026            throws XmlPullParserException, IOException {
20027        String pkgName = null;
20028        int outerDepth = parser.getDepth();
20029        int type;
20030        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20031                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20032            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20033                continue;
20034            }
20035
20036            final String tagName = parser.getName();
20037            if (tagName.equals(TAG_GRANT)) {
20038                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20039                if (DEBUG_BACKUP) {
20040                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20041                }
20042            } else if (tagName.equals(TAG_PERMISSION)) {
20043
20044                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20045                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20046
20047                int newFlagSet = 0;
20048                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20049                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20050                }
20051                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20052                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20053                }
20054                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20055                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20056                }
20057                if (DEBUG_BACKUP) {
20058                    Slog.v(TAG, "  + Restoring grant:"
20059                            + " pkg=" + pkgName
20060                            + " perm=" + permName
20061                            + " granted=" + isGranted
20062                            + " bits=0x" + Integer.toHexString(newFlagSet));
20063                }
20064                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20065                if (ps != null) {
20066                    // Already installed so we apply the grant immediately
20067                    if (DEBUG_BACKUP) {
20068                        Slog.v(TAG, "        + already installed; applying");
20069                    }
20070                    PermissionsState perms = ps.getPermissionsState();
20071                    BasePermission bp =
20072                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20073                    if (bp != null) {
20074                        if (isGranted) {
20075                            perms.grantRuntimePermission(bp, userId);
20076                        }
20077                        if (newFlagSet != 0) {
20078                            perms.updatePermissionFlags(
20079                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20080                        }
20081                    }
20082                } else {
20083                    // Need to wait for post-restore install to apply the grant
20084                    if (DEBUG_BACKUP) {
20085                        Slog.v(TAG, "        - not yet installed; saving for later");
20086                    }
20087                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20088                            isGranted, newFlagSet, userId);
20089                }
20090            } else {
20091                PackageManagerService.reportSettingsProblem(Log.WARN,
20092                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20093                XmlUtils.skipCurrentTag(parser);
20094            }
20095        }
20096
20097        scheduleWriteSettingsLocked();
20098        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20099    }
20100
20101    @Override
20102    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20103            int sourceUserId, int targetUserId, int flags) {
20104        mContext.enforceCallingOrSelfPermission(
20105                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20106        int callingUid = Binder.getCallingUid();
20107        enforceOwnerRights(ownerPackage, callingUid);
20108        PackageManagerServiceUtils.enforceShellRestriction(
20109                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20110        if (intentFilter.countActions() == 0) {
20111            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20112            return;
20113        }
20114        synchronized (mPackages) {
20115            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20116                    ownerPackage, targetUserId, flags);
20117            CrossProfileIntentResolver resolver =
20118                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20119            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20120            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20121            if (existing != null) {
20122                int size = existing.size();
20123                for (int i = 0; i < size; i++) {
20124                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20125                        return;
20126                    }
20127                }
20128            }
20129            resolver.addFilter(newFilter);
20130            scheduleWritePackageRestrictionsLocked(sourceUserId);
20131        }
20132    }
20133
20134    @Override
20135    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20136        mContext.enforceCallingOrSelfPermission(
20137                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20138        final int callingUid = Binder.getCallingUid();
20139        enforceOwnerRights(ownerPackage, callingUid);
20140        PackageManagerServiceUtils.enforceShellRestriction(
20141                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20142        synchronized (mPackages) {
20143            CrossProfileIntentResolver resolver =
20144                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20145            ArraySet<CrossProfileIntentFilter> set =
20146                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20147            for (CrossProfileIntentFilter filter : set) {
20148                if (filter.getOwnerPackage().equals(ownerPackage)) {
20149                    resolver.removeFilter(filter);
20150                }
20151            }
20152            scheduleWritePackageRestrictionsLocked(sourceUserId);
20153        }
20154    }
20155
20156    // Enforcing that callingUid is owning pkg on userId
20157    private void enforceOwnerRights(String pkg, int callingUid) {
20158        // The system owns everything.
20159        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20160            return;
20161        }
20162        final int callingUserId = UserHandle.getUserId(callingUid);
20163        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20164        if (pi == null) {
20165            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20166                    + callingUserId);
20167        }
20168        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20169            throw new SecurityException("Calling uid " + callingUid
20170                    + " does not own package " + pkg);
20171        }
20172    }
20173
20174    @Override
20175    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20176        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20177            return null;
20178        }
20179        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20180    }
20181
20182    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20183        UserManagerService ums = UserManagerService.getInstance();
20184        if (ums != null) {
20185            final UserInfo parent = ums.getProfileParent(userId);
20186            final int launcherUid = (parent != null) ? parent.id : userId;
20187            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20188            if (launcherComponent != null) {
20189                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20190                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20191                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20192                        .setPackage(launcherComponent.getPackageName());
20193                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20194            }
20195        }
20196    }
20197
20198    /**
20199     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20200     * then reports the most likely home activity or null if there are more than one.
20201     */
20202    private ComponentName getDefaultHomeActivity(int userId) {
20203        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20204        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20205        if (cn != null) {
20206            return cn;
20207        }
20208
20209        // Find the launcher with the highest priority and return that component if there are no
20210        // other home activity with the same priority.
20211        int lastPriority = Integer.MIN_VALUE;
20212        ComponentName lastComponent = null;
20213        final int size = allHomeCandidates.size();
20214        for (int i = 0; i < size; i++) {
20215            final ResolveInfo ri = allHomeCandidates.get(i);
20216            if (ri.priority > lastPriority) {
20217                lastComponent = ri.activityInfo.getComponentName();
20218                lastPriority = ri.priority;
20219            } else if (ri.priority == lastPriority) {
20220                // Two components found with same priority.
20221                lastComponent = null;
20222            }
20223        }
20224        return lastComponent;
20225    }
20226
20227    private Intent getHomeIntent() {
20228        Intent intent = new Intent(Intent.ACTION_MAIN);
20229        intent.addCategory(Intent.CATEGORY_HOME);
20230        intent.addCategory(Intent.CATEGORY_DEFAULT);
20231        return intent;
20232    }
20233
20234    private IntentFilter getHomeFilter() {
20235        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20236        filter.addCategory(Intent.CATEGORY_HOME);
20237        filter.addCategory(Intent.CATEGORY_DEFAULT);
20238        return filter;
20239    }
20240
20241    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20242            int userId) {
20243        Intent intent  = getHomeIntent();
20244        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20245                PackageManager.GET_META_DATA, userId);
20246        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20247                true, false, false, userId);
20248
20249        allHomeCandidates.clear();
20250        if (list != null) {
20251            for (ResolveInfo ri : list) {
20252                allHomeCandidates.add(ri);
20253            }
20254        }
20255        return (preferred == null || preferred.activityInfo == null)
20256                ? null
20257                : new ComponentName(preferred.activityInfo.packageName,
20258                        preferred.activityInfo.name);
20259    }
20260
20261    @Override
20262    public void setHomeActivity(ComponentName comp, int userId) {
20263        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20264            return;
20265        }
20266        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20267        getHomeActivitiesAsUser(homeActivities, userId);
20268
20269        boolean found = false;
20270
20271        final int size = homeActivities.size();
20272        final ComponentName[] set = new ComponentName[size];
20273        for (int i = 0; i < size; i++) {
20274            final ResolveInfo candidate = homeActivities.get(i);
20275            final ActivityInfo info = candidate.activityInfo;
20276            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20277            set[i] = activityName;
20278            if (!found && activityName.equals(comp)) {
20279                found = true;
20280            }
20281        }
20282        if (!found) {
20283            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20284                    + userId);
20285        }
20286        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20287                set, comp, userId);
20288    }
20289
20290    private @Nullable String getSetupWizardPackageName() {
20291        final Intent intent = new Intent(Intent.ACTION_MAIN);
20292        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20293
20294        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20295                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20296                        | MATCH_DISABLED_COMPONENTS,
20297                UserHandle.myUserId());
20298        if (matches.size() == 1) {
20299            return matches.get(0).getComponentInfo().packageName;
20300        } else {
20301            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20302                    + ": matches=" + matches);
20303            return null;
20304        }
20305    }
20306
20307    private @Nullable String getStorageManagerPackageName() {
20308        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20309
20310        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20311                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20312                        | MATCH_DISABLED_COMPONENTS,
20313                UserHandle.myUserId());
20314        if (matches.size() == 1) {
20315            return matches.get(0).getComponentInfo().packageName;
20316        } else {
20317            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20318                    + matches.size() + ": matches=" + matches);
20319            return null;
20320        }
20321    }
20322
20323    @Override
20324    public void setApplicationEnabledSetting(String appPackageName,
20325            int newState, int flags, int userId, String callingPackage) {
20326        if (!sUserManager.exists(userId)) return;
20327        if (callingPackage == null) {
20328            callingPackage = Integer.toString(Binder.getCallingUid());
20329        }
20330        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20331    }
20332
20333    @Override
20334    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20335        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20336        synchronized (mPackages) {
20337            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20338            if (pkgSetting != null) {
20339                pkgSetting.setUpdateAvailable(updateAvailable);
20340            }
20341        }
20342    }
20343
20344    @Override
20345    public void setComponentEnabledSetting(ComponentName componentName,
20346            int newState, int flags, int userId) {
20347        if (!sUserManager.exists(userId)) return;
20348        setEnabledSetting(componentName.getPackageName(),
20349                componentName.getClassName(), newState, flags, userId, null);
20350    }
20351
20352    private void setEnabledSetting(final String packageName, String className, int newState,
20353            final int flags, int userId, String callingPackage) {
20354        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20355              || newState == COMPONENT_ENABLED_STATE_ENABLED
20356              || newState == COMPONENT_ENABLED_STATE_DISABLED
20357              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20358              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20359            throw new IllegalArgumentException("Invalid new component state: "
20360                    + newState);
20361        }
20362        PackageSetting pkgSetting;
20363        final int callingUid = Binder.getCallingUid();
20364        final int permission;
20365        if (callingUid == Process.SYSTEM_UID) {
20366            permission = PackageManager.PERMISSION_GRANTED;
20367        } else {
20368            permission = mContext.checkCallingOrSelfPermission(
20369                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20370        }
20371        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20372                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20373        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20374        boolean sendNow = false;
20375        boolean isApp = (className == null);
20376        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20377        String componentName = isApp ? packageName : className;
20378        int packageUid = -1;
20379        ArrayList<String> components;
20380
20381        // reader
20382        synchronized (mPackages) {
20383            pkgSetting = mSettings.mPackages.get(packageName);
20384            if (pkgSetting == null) {
20385                if (!isCallerInstantApp) {
20386                    if (className == null) {
20387                        throw new IllegalArgumentException("Unknown package: " + packageName);
20388                    }
20389                    throw new IllegalArgumentException(
20390                            "Unknown component: " + packageName + "/" + className);
20391                } else {
20392                    // throw SecurityException to prevent leaking package information
20393                    throw new SecurityException(
20394                            "Attempt to change component state; "
20395                            + "pid=" + Binder.getCallingPid()
20396                            + ", uid=" + callingUid
20397                            + (className == null
20398                                    ? ", package=" + packageName
20399                                    : ", component=" + packageName + "/" + className));
20400                }
20401            }
20402        }
20403
20404        // Limit who can change which apps
20405        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20406            // Don't allow apps that don't have permission to modify other apps
20407            if (!allowedByPermission
20408                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20409                throw new SecurityException(
20410                        "Attempt to change component state; "
20411                        + "pid=" + Binder.getCallingPid()
20412                        + ", uid=" + callingUid
20413                        + (className == null
20414                                ? ", package=" + packageName
20415                                : ", component=" + packageName + "/" + className));
20416            }
20417            // Don't allow changing protected packages.
20418            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20419                throw new SecurityException("Cannot disable a protected package: " + packageName);
20420            }
20421        }
20422
20423        synchronized (mPackages) {
20424            if (callingUid == Process.SHELL_UID
20425                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20426                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20427                // unless it is a test package.
20428                int oldState = pkgSetting.getEnabled(userId);
20429                if (className == null
20430                        &&
20431                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20432                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20433                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20434                        &&
20435                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20436                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20437                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20438                    // ok
20439                } else {
20440                    throw new SecurityException(
20441                            "Shell cannot change component state for " + packageName + "/"
20442                                    + className + " to " + newState);
20443                }
20444            }
20445        }
20446        if (className == null) {
20447            // We're dealing with an application/package level state change
20448            synchronized (mPackages) {
20449                if (pkgSetting.getEnabled(userId) == newState) {
20450                    // Nothing to do
20451                    return;
20452                }
20453            }
20454            // If we're enabling a system stub, there's a little more work to do.
20455            // Prior to enabling the package, we need to decompress the APK(s) to the
20456            // data partition and then replace the version on the system partition.
20457            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20458            final boolean isSystemStub = deletedPkg.isStub
20459                    && deletedPkg.isSystem();
20460            if (isSystemStub
20461                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20462                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20463                final File codePath = decompressPackage(deletedPkg);
20464                if (codePath == null) {
20465                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20466                    return;
20467                }
20468                // TODO remove direct parsing of the package object during internal cleanup
20469                // of scan package
20470                // We need to call parse directly here for no other reason than we need
20471                // the new package in order to disable the old one [we use the information
20472                // for some internal optimization to optionally create a new package setting
20473                // object on replace]. However, we can't get the package from the scan
20474                // because the scan modifies live structures and we need to remove the
20475                // old [system] package from the system before a scan can be attempted.
20476                // Once scan is indempotent we can remove this parse and use the package
20477                // object we scanned, prior to adding it to package settings.
20478                final PackageParser pp = new PackageParser();
20479                pp.setSeparateProcesses(mSeparateProcesses);
20480                pp.setDisplayMetrics(mMetrics);
20481                pp.setCallback(mPackageParserCallback);
20482                final PackageParser.Package tmpPkg;
20483                try {
20484                    final @ParseFlags int parseFlags = mDefParseFlags
20485                            | PackageParser.PARSE_MUST_BE_APK
20486                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20487                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20488                } catch (PackageParserException e) {
20489                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20490                    return;
20491                }
20492                synchronized (mInstallLock) {
20493                    // Disable the stub and remove any package entries
20494                    removePackageLI(deletedPkg, true);
20495                    synchronized (mPackages) {
20496                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20497                    }
20498                    final PackageParser.Package pkg;
20499                    try (PackageFreezer freezer =
20500                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20501                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20502                                | PackageParser.PARSE_ENFORCE_CODE;
20503                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20504                                0 /*currentTime*/, null /*user*/);
20505                        prepareAppDataAfterInstallLIF(pkg);
20506                        synchronized (mPackages) {
20507                            try {
20508                                updateSharedLibrariesLPr(pkg, null);
20509                            } catch (PackageManagerException e) {
20510                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20511                            }
20512                            mPermissionManager.updatePermissions(
20513                                    pkg.packageName, pkg, true, mPackages.values(),
20514                                    mPermissionCallback);
20515                            mSettings.writeLPr();
20516                        }
20517                    } catch (PackageManagerException e) {
20518                        // Whoops! Something went wrong; try to roll back to the stub
20519                        Slog.w(TAG, "Failed to install compressed system package:"
20520                                + pkgSetting.name, e);
20521                        // Remove the failed install
20522                        removeCodePathLI(codePath);
20523
20524                        // Install the system package
20525                        try (PackageFreezer freezer =
20526                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20527                            synchronized (mPackages) {
20528                                // NOTE: The system package always needs to be enabled; even
20529                                // if it's for a compressed stub. If we don't, installing the
20530                                // system package fails during scan [scanning checks the disabled
20531                                // packages]. We will reverse this later, after we've "installed"
20532                                // the stub.
20533                                // This leaves us in a fragile state; the stub should never be
20534                                // enabled, so, cross your fingers and hope nothing goes wrong
20535                                // until we can disable the package later.
20536                                enableSystemPackageLPw(deletedPkg);
20537                            }
20538                            installPackageFromSystemLIF(deletedPkg.codePath,
20539                                    false /*isPrivileged*/, null /*allUserHandles*/,
20540                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20541                                    true /*writeSettings*/);
20542                        } catch (PackageManagerException pme) {
20543                            Slog.w(TAG, "Failed to restore system package:"
20544                                    + deletedPkg.packageName, pme);
20545                        } finally {
20546                            synchronized (mPackages) {
20547                                mSettings.disableSystemPackageLPw(
20548                                        deletedPkg.packageName, true /*replaced*/);
20549                                mSettings.writeLPr();
20550                            }
20551                        }
20552                        return;
20553                    }
20554                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20555                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20556                    mDexManager.notifyPackageUpdated(pkg.packageName,
20557                            pkg.baseCodePath, pkg.splitCodePaths);
20558                }
20559            }
20560            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20561                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20562                // Don't care about who enables an app.
20563                callingPackage = null;
20564            }
20565            synchronized (mPackages) {
20566                pkgSetting.setEnabled(newState, userId, callingPackage);
20567            }
20568        } else {
20569            synchronized (mPackages) {
20570                // We're dealing with a component level state change
20571                // First, verify that this is a valid class name.
20572                PackageParser.Package pkg = pkgSetting.pkg;
20573                if (pkg == null || !pkg.hasComponentClassName(className)) {
20574                    if (pkg != null &&
20575                            pkg.applicationInfo.targetSdkVersion >=
20576                                    Build.VERSION_CODES.JELLY_BEAN) {
20577                        throw new IllegalArgumentException("Component class " + className
20578                                + " does not exist in " + packageName);
20579                    } else {
20580                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20581                                + className + " does not exist in " + packageName);
20582                    }
20583                }
20584                switch (newState) {
20585                    case COMPONENT_ENABLED_STATE_ENABLED:
20586                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20587                            return;
20588                        }
20589                        break;
20590                    case COMPONENT_ENABLED_STATE_DISABLED:
20591                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20592                            return;
20593                        }
20594                        break;
20595                    case COMPONENT_ENABLED_STATE_DEFAULT:
20596                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20597                            return;
20598                        }
20599                        break;
20600                    default:
20601                        Slog.e(TAG, "Invalid new component state: " + newState);
20602                        return;
20603                }
20604            }
20605        }
20606        synchronized (mPackages) {
20607            scheduleWritePackageRestrictionsLocked(userId);
20608            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20609            final long callingId = Binder.clearCallingIdentity();
20610            try {
20611                updateInstantAppInstallerLocked(packageName);
20612            } finally {
20613                Binder.restoreCallingIdentity(callingId);
20614            }
20615            components = mPendingBroadcasts.get(userId, packageName);
20616            final boolean newPackage = components == null;
20617            if (newPackage) {
20618                components = new ArrayList<String>();
20619            }
20620            if (!components.contains(componentName)) {
20621                components.add(componentName);
20622            }
20623            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20624                sendNow = true;
20625                // Purge entry from pending broadcast list if another one exists already
20626                // since we are sending one right away.
20627                mPendingBroadcasts.remove(userId, packageName);
20628            } else {
20629                if (newPackage) {
20630                    mPendingBroadcasts.put(userId, packageName, components);
20631                }
20632                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20633                    // Schedule a message
20634                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20635                }
20636            }
20637        }
20638
20639        long callingId = Binder.clearCallingIdentity();
20640        try {
20641            if (sendNow) {
20642                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20643                sendPackageChangedBroadcast(packageName,
20644                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20645            }
20646        } finally {
20647            Binder.restoreCallingIdentity(callingId);
20648        }
20649    }
20650
20651    @Override
20652    public void flushPackageRestrictionsAsUser(int userId) {
20653        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20654            return;
20655        }
20656        if (!sUserManager.exists(userId)) {
20657            return;
20658        }
20659        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20660                false /* checkShell */, "flushPackageRestrictions");
20661        synchronized (mPackages) {
20662            mSettings.writePackageRestrictionsLPr(userId);
20663            mDirtyUsers.remove(userId);
20664            if (mDirtyUsers.isEmpty()) {
20665                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20666            }
20667        }
20668    }
20669
20670    private void sendPackageChangedBroadcast(String packageName,
20671            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20672        if (DEBUG_INSTALL)
20673            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20674                    + componentNames);
20675        Bundle extras = new Bundle(4);
20676        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20677        String nameList[] = new String[componentNames.size()];
20678        componentNames.toArray(nameList);
20679        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20680        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20681        extras.putInt(Intent.EXTRA_UID, packageUid);
20682        // If this is not reporting a change of the overall package, then only send it
20683        // to registered receivers.  We don't want to launch a swath of apps for every
20684        // little component state change.
20685        final int flags = !componentNames.contains(packageName)
20686                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20687        final int userId = UserHandle.getUserId(packageUid);
20688        final boolean isInstantApp = isInstantApp(packageName, userId);
20689        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20690        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20691        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20692                userIds, instantUserIds);
20693    }
20694
20695    @Override
20696    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20697        if (!sUserManager.exists(userId)) return;
20698        final int callingUid = Binder.getCallingUid();
20699        if (getInstantAppPackageName(callingUid) != null) {
20700            return;
20701        }
20702        final int permission = mContext.checkCallingOrSelfPermission(
20703                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20704        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20705        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20706                true /* requireFullPermission */, true /* checkShell */, "stop package");
20707        // writer
20708        synchronized (mPackages) {
20709            final PackageSetting ps = mSettings.mPackages.get(packageName);
20710            if (!filterAppAccessLPr(ps, callingUid, userId)
20711                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20712                            allowedByPermission, callingUid, userId)) {
20713                scheduleWritePackageRestrictionsLocked(userId);
20714            }
20715        }
20716    }
20717
20718    @Override
20719    public String getInstallerPackageName(String packageName) {
20720        final int callingUid = Binder.getCallingUid();
20721        if (getInstantAppPackageName(callingUid) != null) {
20722            return null;
20723        }
20724        // reader
20725        synchronized (mPackages) {
20726            final PackageSetting ps = mSettings.mPackages.get(packageName);
20727            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20728                return null;
20729            }
20730            return mSettings.getInstallerPackageNameLPr(packageName);
20731        }
20732    }
20733
20734    public boolean isOrphaned(String packageName) {
20735        // reader
20736        synchronized (mPackages) {
20737            return mSettings.isOrphaned(packageName);
20738        }
20739    }
20740
20741    @Override
20742    public int getApplicationEnabledSetting(String packageName, int userId) {
20743        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20744        int callingUid = Binder.getCallingUid();
20745        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20746                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20747        // reader
20748        synchronized (mPackages) {
20749            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20750                return COMPONENT_ENABLED_STATE_DISABLED;
20751            }
20752            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20753        }
20754    }
20755
20756    @Override
20757    public int getComponentEnabledSetting(ComponentName component, int userId) {
20758        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20759        int callingUid = Binder.getCallingUid();
20760        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20761                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20762        synchronized (mPackages) {
20763            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20764                    component, TYPE_UNKNOWN, userId)) {
20765                return COMPONENT_ENABLED_STATE_DISABLED;
20766            }
20767            return mSettings.getComponentEnabledSettingLPr(component, userId);
20768        }
20769    }
20770
20771    @Override
20772    public void enterSafeMode() {
20773        enforceSystemOrRoot("Only the system can request entering safe mode");
20774
20775        if (!mSystemReady) {
20776            mSafeMode = true;
20777        }
20778    }
20779
20780    @Override
20781    public void systemReady() {
20782        enforceSystemOrRoot("Only the system can claim the system is ready");
20783
20784        mSystemReady = true;
20785        final ContentResolver resolver = mContext.getContentResolver();
20786        ContentObserver co = new ContentObserver(mHandler) {
20787            @Override
20788            public void onChange(boolean selfChange) {
20789                mEphemeralAppsDisabled =
20790                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20791                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20792            }
20793        };
20794        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20795                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20796                false, co, UserHandle.USER_SYSTEM);
20797        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20798                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20799        co.onChange(true);
20800
20801        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20802        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20803        // it is done.
20804        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20805            @Override
20806            public void onChange(boolean selfChange) {
20807                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20808                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20809                        oobEnabled == 1 ? "true" : "false");
20810            }
20811        };
20812        mContext.getContentResolver().registerContentObserver(
20813                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20814                UserHandle.USER_SYSTEM);
20815        // At boot, restore the value from the setting, which persists across reboot.
20816        privAppOobObserver.onChange(true);
20817
20818        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20819        // disabled after already being started.
20820        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20821                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20822
20823        // Read the compatibilty setting when the system is ready.
20824        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20825                mContext.getContentResolver(),
20826                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20827        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20828        if (DEBUG_SETTINGS) {
20829            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20830        }
20831
20832        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20833
20834        synchronized (mPackages) {
20835            // Verify that all of the preferred activity components actually
20836            // exist.  It is possible for applications to be updated and at
20837            // that point remove a previously declared activity component that
20838            // had been set as a preferred activity.  We try to clean this up
20839            // the next time we encounter that preferred activity, but it is
20840            // possible for the user flow to never be able to return to that
20841            // situation so here we do a sanity check to make sure we haven't
20842            // left any junk around.
20843            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20844            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20845                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20846                removed.clear();
20847                for (PreferredActivity pa : pir.filterSet()) {
20848                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20849                        removed.add(pa);
20850                    }
20851                }
20852                if (removed.size() > 0) {
20853                    for (int r=0; r<removed.size(); r++) {
20854                        PreferredActivity pa = removed.get(r);
20855                        Slog.w(TAG, "Removing dangling preferred activity: "
20856                                + pa.mPref.mComponent);
20857                        pir.removeFilter(pa);
20858                    }
20859                    mSettings.writePackageRestrictionsLPr(
20860                            mSettings.mPreferredActivities.keyAt(i));
20861                }
20862            }
20863
20864            for (int userId : UserManagerService.getInstance().getUserIds()) {
20865                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20866                    grantPermissionsUserIds = ArrayUtils.appendInt(
20867                            grantPermissionsUserIds, userId);
20868                }
20869            }
20870        }
20871        sUserManager.systemReady();
20872        // If we upgraded grant all default permissions before kicking off.
20873        for (int userId : grantPermissionsUserIds) {
20874            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20875        }
20876
20877        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20878            // If we did not grant default permissions, we preload from this the
20879            // default permission exceptions lazily to ensure we don't hit the
20880            // disk on a new user creation.
20881            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20882        }
20883
20884        // Now that we've scanned all packages, and granted any default
20885        // permissions, ensure permissions are updated. Beware of dragons if you
20886        // try optimizing this.
20887        synchronized (mPackages) {
20888            mPermissionManager.updateAllPermissions(
20889                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20890                    mPermissionCallback);
20891        }
20892
20893        // Kick off any messages waiting for system ready
20894        if (mPostSystemReadyMessages != null) {
20895            for (Message msg : mPostSystemReadyMessages) {
20896                msg.sendToTarget();
20897            }
20898            mPostSystemReadyMessages = null;
20899        }
20900
20901        // Watch for external volumes that come and go over time
20902        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20903        storage.registerListener(mStorageListener);
20904
20905        mInstallerService.systemReady();
20906        mPackageDexOptimizer.systemReady();
20907
20908        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20909                StorageManagerInternal.class);
20910        StorageManagerInternal.addExternalStoragePolicy(
20911                new StorageManagerInternal.ExternalStorageMountPolicy() {
20912            @Override
20913            public int getMountMode(int uid, String packageName) {
20914                if (Process.isIsolated(uid)) {
20915                    return Zygote.MOUNT_EXTERNAL_NONE;
20916                }
20917                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20918                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20919                }
20920                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20921                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20922                }
20923                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20924                    return Zygote.MOUNT_EXTERNAL_READ;
20925                }
20926                return Zygote.MOUNT_EXTERNAL_WRITE;
20927            }
20928
20929            @Override
20930            public boolean hasExternalStorage(int uid, String packageName) {
20931                return true;
20932            }
20933        });
20934
20935        // Now that we're mostly running, clean up stale users and apps
20936        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20937        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20938
20939        mPermissionManager.systemReady();
20940    }
20941
20942    public void waitForAppDataPrepared() {
20943        if (mPrepareAppDataFuture == null) {
20944            return;
20945        }
20946        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20947        mPrepareAppDataFuture = null;
20948    }
20949
20950    @Override
20951    public boolean isSafeMode() {
20952        // allow instant applications
20953        return mSafeMode;
20954    }
20955
20956    @Override
20957    public boolean hasSystemUidErrors() {
20958        // allow instant applications
20959        return mHasSystemUidErrors;
20960    }
20961
20962    static String arrayToString(int[] array) {
20963        StringBuffer buf = new StringBuffer(128);
20964        buf.append('[');
20965        if (array != null) {
20966            for (int i=0; i<array.length; i++) {
20967                if (i > 0) buf.append(", ");
20968                buf.append(array[i]);
20969            }
20970        }
20971        buf.append(']');
20972        return buf.toString();
20973    }
20974
20975    @Override
20976    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20977            FileDescriptor err, String[] args, ShellCallback callback,
20978            ResultReceiver resultReceiver) {
20979        (new PackageManagerShellCommand(this)).exec(
20980                this, in, out, err, args, callback, resultReceiver);
20981    }
20982
20983    @Override
20984    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20985        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20986
20987        DumpState dumpState = new DumpState();
20988        boolean fullPreferred = false;
20989        boolean checkin = false;
20990
20991        String packageName = null;
20992        ArraySet<String> permissionNames = null;
20993
20994        int opti = 0;
20995        while (opti < args.length) {
20996            String opt = args[opti];
20997            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20998                break;
20999            }
21000            opti++;
21001
21002            if ("-a".equals(opt)) {
21003                // Right now we only know how to print all.
21004            } else if ("-h".equals(opt)) {
21005                pw.println("Package manager dump options:");
21006                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21007                pw.println("    --checkin: dump for a checkin");
21008                pw.println("    -f: print details of intent filters");
21009                pw.println("    -h: print this help");
21010                pw.println("  cmd may be one of:");
21011                pw.println("    l[ibraries]: list known shared libraries");
21012                pw.println("    f[eatures]: list device features");
21013                pw.println("    k[eysets]: print known keysets");
21014                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21015                pw.println("    perm[issions]: dump permissions");
21016                pw.println("    permission [name ...]: dump declaration and use of given permission");
21017                pw.println("    pref[erred]: print preferred package settings");
21018                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21019                pw.println("    prov[iders]: dump content providers");
21020                pw.println("    p[ackages]: dump installed packages");
21021                pw.println("    s[hared-users]: dump shared user IDs");
21022                pw.println("    m[essages]: print collected runtime messages");
21023                pw.println("    v[erifiers]: print package verifier info");
21024                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21025                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21026                pw.println("    version: print database version info");
21027                pw.println("    write: write current settings now");
21028                pw.println("    installs: details about install sessions");
21029                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21030                pw.println("    dexopt: dump dexopt state");
21031                pw.println("    compiler-stats: dump compiler statistics");
21032                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21033                pw.println("    service-permissions: dump permissions required by services");
21034                pw.println("    <package.name>: info about given package");
21035                return;
21036            } else if ("--checkin".equals(opt)) {
21037                checkin = true;
21038            } else if ("-f".equals(opt)) {
21039                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21040            } else if ("--proto".equals(opt)) {
21041                dumpProto(fd);
21042                return;
21043            } else {
21044                pw.println("Unknown argument: " + opt + "; use -h for help");
21045            }
21046        }
21047
21048        // Is the caller requesting to dump a particular piece of data?
21049        if (opti < args.length) {
21050            String cmd = args[opti];
21051            opti++;
21052            // Is this a package name?
21053            if ("android".equals(cmd) || cmd.contains(".")) {
21054                packageName = cmd;
21055                // When dumping a single package, we always dump all of its
21056                // filter information since the amount of data will be reasonable.
21057                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21058            } else if ("check-permission".equals(cmd)) {
21059                if (opti >= args.length) {
21060                    pw.println("Error: check-permission missing permission argument");
21061                    return;
21062                }
21063                String perm = args[opti];
21064                opti++;
21065                if (opti >= args.length) {
21066                    pw.println("Error: check-permission missing package argument");
21067                    return;
21068                }
21069
21070                String pkg = args[opti];
21071                opti++;
21072                int user = UserHandle.getUserId(Binder.getCallingUid());
21073                if (opti < args.length) {
21074                    try {
21075                        user = Integer.parseInt(args[opti]);
21076                    } catch (NumberFormatException e) {
21077                        pw.println("Error: check-permission user argument is not a number: "
21078                                + args[opti]);
21079                        return;
21080                    }
21081                }
21082
21083                // Normalize package name to handle renamed packages and static libs
21084                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21085
21086                pw.println(checkPermission(perm, pkg, user));
21087                return;
21088            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21089                dumpState.setDump(DumpState.DUMP_LIBS);
21090            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21091                dumpState.setDump(DumpState.DUMP_FEATURES);
21092            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21093                if (opti >= args.length) {
21094                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21095                            | DumpState.DUMP_SERVICE_RESOLVERS
21096                            | DumpState.DUMP_RECEIVER_RESOLVERS
21097                            | DumpState.DUMP_CONTENT_RESOLVERS);
21098                } else {
21099                    while (opti < args.length) {
21100                        String name = args[opti];
21101                        if ("a".equals(name) || "activity".equals(name)) {
21102                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21103                        } else if ("s".equals(name) || "service".equals(name)) {
21104                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21105                        } else if ("r".equals(name) || "receiver".equals(name)) {
21106                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21107                        } else if ("c".equals(name) || "content".equals(name)) {
21108                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21109                        } else {
21110                            pw.println("Error: unknown resolver table type: " + name);
21111                            return;
21112                        }
21113                        opti++;
21114                    }
21115                }
21116            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21117                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21118            } else if ("permission".equals(cmd)) {
21119                if (opti >= args.length) {
21120                    pw.println("Error: permission requires permission name");
21121                    return;
21122                }
21123                permissionNames = new ArraySet<>();
21124                while (opti < args.length) {
21125                    permissionNames.add(args[opti]);
21126                    opti++;
21127                }
21128                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21129                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21130            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21131                dumpState.setDump(DumpState.DUMP_PREFERRED);
21132            } else if ("preferred-xml".equals(cmd)) {
21133                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21134                if (opti < args.length && "--full".equals(args[opti])) {
21135                    fullPreferred = true;
21136                    opti++;
21137                }
21138            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21139                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21140            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21141                dumpState.setDump(DumpState.DUMP_PACKAGES);
21142            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21143                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21144            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21145                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21146            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21147                dumpState.setDump(DumpState.DUMP_MESSAGES);
21148            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21149                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21150            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21151                    || "intent-filter-verifiers".equals(cmd)) {
21152                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21153            } else if ("version".equals(cmd)) {
21154                dumpState.setDump(DumpState.DUMP_VERSION);
21155            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21156                dumpState.setDump(DumpState.DUMP_KEYSETS);
21157            } else if ("installs".equals(cmd)) {
21158                dumpState.setDump(DumpState.DUMP_INSTALLS);
21159            } else if ("frozen".equals(cmd)) {
21160                dumpState.setDump(DumpState.DUMP_FROZEN);
21161            } else if ("volumes".equals(cmd)) {
21162                dumpState.setDump(DumpState.DUMP_VOLUMES);
21163            } else if ("dexopt".equals(cmd)) {
21164                dumpState.setDump(DumpState.DUMP_DEXOPT);
21165            } else if ("compiler-stats".equals(cmd)) {
21166                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21167            } else if ("changes".equals(cmd)) {
21168                dumpState.setDump(DumpState.DUMP_CHANGES);
21169            } else if ("service-permissions".equals(cmd)) {
21170                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21171            } else if ("write".equals(cmd)) {
21172                synchronized (mPackages) {
21173                    mSettings.writeLPr();
21174                    pw.println("Settings written.");
21175                    return;
21176                }
21177            }
21178        }
21179
21180        if (checkin) {
21181            pw.println("vers,1");
21182        }
21183
21184        // reader
21185        synchronized (mPackages) {
21186            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21187                if (!checkin) {
21188                    if (dumpState.onTitlePrinted())
21189                        pw.println();
21190                    pw.println("Database versions:");
21191                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21192                }
21193            }
21194
21195            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21196                if (!checkin) {
21197                    if (dumpState.onTitlePrinted())
21198                        pw.println();
21199                    pw.println("Verifiers:");
21200                    pw.print("  Required: ");
21201                    pw.print(mRequiredVerifierPackage);
21202                    pw.print(" (uid=");
21203                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21204                            UserHandle.USER_SYSTEM));
21205                    pw.println(")");
21206                } else if (mRequiredVerifierPackage != null) {
21207                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21208                    pw.print(",");
21209                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21210                            UserHandle.USER_SYSTEM));
21211                }
21212            }
21213
21214            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21215                    packageName == null) {
21216                if (mIntentFilterVerifierComponent != null) {
21217                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21218                    if (!checkin) {
21219                        if (dumpState.onTitlePrinted())
21220                            pw.println();
21221                        pw.println("Intent Filter Verifier:");
21222                        pw.print("  Using: ");
21223                        pw.print(verifierPackageName);
21224                        pw.print(" (uid=");
21225                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21226                                UserHandle.USER_SYSTEM));
21227                        pw.println(")");
21228                    } else if (verifierPackageName != null) {
21229                        pw.print("ifv,"); pw.print(verifierPackageName);
21230                        pw.print(",");
21231                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21232                                UserHandle.USER_SYSTEM));
21233                    }
21234                } else {
21235                    pw.println();
21236                    pw.println("No Intent Filter Verifier available!");
21237                }
21238            }
21239
21240            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21241                boolean printedHeader = false;
21242                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21243                while (it.hasNext()) {
21244                    String libName = it.next();
21245                    LongSparseArray<SharedLibraryEntry> versionedLib
21246                            = mSharedLibraries.get(libName);
21247                    if (versionedLib == null) {
21248                        continue;
21249                    }
21250                    final int versionCount = versionedLib.size();
21251                    for (int i = 0; i < versionCount; i++) {
21252                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21253                        if (!checkin) {
21254                            if (!printedHeader) {
21255                                if (dumpState.onTitlePrinted())
21256                                    pw.println();
21257                                pw.println("Libraries:");
21258                                printedHeader = true;
21259                            }
21260                            pw.print("  ");
21261                        } else {
21262                            pw.print("lib,");
21263                        }
21264                        pw.print(libEntry.info.getName());
21265                        if (libEntry.info.isStatic()) {
21266                            pw.print(" version=" + libEntry.info.getLongVersion());
21267                        }
21268                        if (!checkin) {
21269                            pw.print(" -> ");
21270                        }
21271                        if (libEntry.path != null) {
21272                            pw.print(" (jar) ");
21273                            pw.print(libEntry.path);
21274                        } else {
21275                            pw.print(" (apk) ");
21276                            pw.print(libEntry.apk);
21277                        }
21278                        pw.println();
21279                    }
21280                }
21281            }
21282
21283            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21284                if (dumpState.onTitlePrinted())
21285                    pw.println();
21286                if (!checkin) {
21287                    pw.println("Features:");
21288                }
21289
21290                synchronized (mAvailableFeatures) {
21291                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21292                        if (checkin) {
21293                            pw.print("feat,");
21294                            pw.print(feat.name);
21295                            pw.print(",");
21296                            pw.println(feat.version);
21297                        } else {
21298                            pw.print("  ");
21299                            pw.print(feat.name);
21300                            if (feat.version > 0) {
21301                                pw.print(" version=");
21302                                pw.print(feat.version);
21303                            }
21304                            pw.println();
21305                        }
21306                    }
21307                }
21308            }
21309
21310            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21311                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21312                        : "Activity Resolver Table:", "  ", packageName,
21313                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21314                    dumpState.setTitlePrinted(true);
21315                }
21316            }
21317            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21318                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21319                        : "Receiver Resolver Table:", "  ", packageName,
21320                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21321                    dumpState.setTitlePrinted(true);
21322                }
21323            }
21324            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21325                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21326                        : "Service Resolver Table:", "  ", packageName,
21327                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21328                    dumpState.setTitlePrinted(true);
21329                }
21330            }
21331            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21332                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21333                        : "Provider Resolver Table:", "  ", packageName,
21334                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21335                    dumpState.setTitlePrinted(true);
21336                }
21337            }
21338
21339            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21340                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21341                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21342                    int user = mSettings.mPreferredActivities.keyAt(i);
21343                    if (pir.dump(pw,
21344                            dumpState.getTitlePrinted()
21345                                ? "\nPreferred Activities User " + user + ":"
21346                                : "Preferred Activities User " + user + ":", "  ",
21347                            packageName, true, false)) {
21348                        dumpState.setTitlePrinted(true);
21349                    }
21350                }
21351            }
21352
21353            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21354                pw.flush();
21355                FileOutputStream fout = new FileOutputStream(fd);
21356                BufferedOutputStream str = new BufferedOutputStream(fout);
21357                XmlSerializer serializer = new FastXmlSerializer();
21358                try {
21359                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21360                    serializer.startDocument(null, true);
21361                    serializer.setFeature(
21362                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21363                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21364                    serializer.endDocument();
21365                    serializer.flush();
21366                } catch (IllegalArgumentException e) {
21367                    pw.println("Failed writing: " + e);
21368                } catch (IllegalStateException e) {
21369                    pw.println("Failed writing: " + e);
21370                } catch (IOException e) {
21371                    pw.println("Failed writing: " + e);
21372                }
21373            }
21374
21375            if (!checkin
21376                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21377                    && packageName == null) {
21378                pw.println();
21379                int count = mSettings.mPackages.size();
21380                if (count == 0) {
21381                    pw.println("No applications!");
21382                    pw.println();
21383                } else {
21384                    final String prefix = "  ";
21385                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21386                    if (allPackageSettings.size() == 0) {
21387                        pw.println("No domain preferred apps!");
21388                        pw.println();
21389                    } else {
21390                        pw.println("App verification status:");
21391                        pw.println();
21392                        count = 0;
21393                        for (PackageSetting ps : allPackageSettings) {
21394                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21395                            if (ivi == null || ivi.getPackageName() == null) continue;
21396                            pw.println(prefix + "Package: " + ivi.getPackageName());
21397                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21398                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21399                            pw.println();
21400                            count++;
21401                        }
21402                        if (count == 0) {
21403                            pw.println(prefix + "No app verification established.");
21404                            pw.println();
21405                        }
21406                        for (int userId : sUserManager.getUserIds()) {
21407                            pw.println("App linkages for user " + userId + ":");
21408                            pw.println();
21409                            count = 0;
21410                            for (PackageSetting ps : allPackageSettings) {
21411                                final long status = ps.getDomainVerificationStatusForUser(userId);
21412                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21413                                        && !DEBUG_DOMAIN_VERIFICATION) {
21414                                    continue;
21415                                }
21416                                pw.println(prefix + "Package: " + ps.name);
21417                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21418                                String statusStr = IntentFilterVerificationInfo.
21419                                        getStatusStringFromValue(status);
21420                                pw.println(prefix + "Status:  " + statusStr);
21421                                pw.println();
21422                                count++;
21423                            }
21424                            if (count == 0) {
21425                                pw.println(prefix + "No configured app linkages.");
21426                                pw.println();
21427                            }
21428                        }
21429                    }
21430                }
21431            }
21432
21433            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21434                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21435            }
21436
21437            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21438                boolean printedSomething = false;
21439                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21440                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21441                        continue;
21442                    }
21443                    if (!printedSomething) {
21444                        if (dumpState.onTitlePrinted())
21445                            pw.println();
21446                        pw.println("Registered ContentProviders:");
21447                        printedSomething = true;
21448                    }
21449                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21450                    pw.print("    "); pw.println(p.toString());
21451                }
21452                printedSomething = false;
21453                for (Map.Entry<String, PackageParser.Provider> entry :
21454                        mProvidersByAuthority.entrySet()) {
21455                    PackageParser.Provider p = entry.getValue();
21456                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21457                        continue;
21458                    }
21459                    if (!printedSomething) {
21460                        if (dumpState.onTitlePrinted())
21461                            pw.println();
21462                        pw.println("ContentProvider Authorities:");
21463                        printedSomething = true;
21464                    }
21465                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21466                    pw.print("    "); pw.println(p.toString());
21467                    if (p.info != null && p.info.applicationInfo != null) {
21468                        final String appInfo = p.info.applicationInfo.toString();
21469                        pw.print("      applicationInfo="); pw.println(appInfo);
21470                    }
21471                }
21472            }
21473
21474            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21475                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21476            }
21477
21478            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21479                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21480            }
21481
21482            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21483                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21484            }
21485
21486            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21487                if (dumpState.onTitlePrinted()) pw.println();
21488                pw.println("Package Changes:");
21489                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21490                final int K = mChangedPackages.size();
21491                for (int i = 0; i < K; i++) {
21492                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21493                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21494                    final int N = changes.size();
21495                    if (N == 0) {
21496                        pw.print("    "); pw.println("No packages changed");
21497                    } else {
21498                        for (int j = 0; j < N; j++) {
21499                            final String pkgName = changes.valueAt(j);
21500                            final int sequenceNumber = changes.keyAt(j);
21501                            pw.print("    ");
21502                            pw.print("seq=");
21503                            pw.print(sequenceNumber);
21504                            pw.print(", package=");
21505                            pw.println(pkgName);
21506                        }
21507                    }
21508                }
21509            }
21510
21511            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21512                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21513            }
21514
21515            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21516                // XXX should handle packageName != null by dumping only install data that
21517                // the given package is involved with.
21518                if (dumpState.onTitlePrinted()) pw.println();
21519
21520                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21521                ipw.println();
21522                ipw.println("Frozen packages:");
21523                ipw.increaseIndent();
21524                if (mFrozenPackages.size() == 0) {
21525                    ipw.println("(none)");
21526                } else {
21527                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21528                        ipw.println(mFrozenPackages.valueAt(i));
21529                    }
21530                }
21531                ipw.decreaseIndent();
21532            }
21533
21534            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21535                if (dumpState.onTitlePrinted()) pw.println();
21536
21537                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21538                ipw.println();
21539                ipw.println("Loaded volumes:");
21540                ipw.increaseIndent();
21541                if (mLoadedVolumes.size() == 0) {
21542                    ipw.println("(none)");
21543                } else {
21544                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21545                        ipw.println(mLoadedVolumes.valueAt(i));
21546                    }
21547                }
21548                ipw.decreaseIndent();
21549            }
21550
21551            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21552                    && packageName == null) {
21553                if (dumpState.onTitlePrinted()) pw.println();
21554                pw.println("Service permissions:");
21555
21556                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21557                while (filterIterator.hasNext()) {
21558                    final ServiceIntentInfo info = filterIterator.next();
21559                    final ServiceInfo serviceInfo = info.service.info;
21560                    final String permission = serviceInfo.permission;
21561                    if (permission != null) {
21562                        pw.print("    ");
21563                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21564                        pw.print(": ");
21565                        pw.println(permission);
21566                    }
21567                }
21568            }
21569
21570            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21571                if (dumpState.onTitlePrinted()) pw.println();
21572                dumpDexoptStateLPr(pw, packageName);
21573            }
21574
21575            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21576                if (dumpState.onTitlePrinted()) pw.println();
21577                dumpCompilerStatsLPr(pw, packageName);
21578            }
21579
21580            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21581                if (dumpState.onTitlePrinted()) pw.println();
21582                mSettings.dumpReadMessagesLPr(pw, dumpState);
21583
21584                pw.println();
21585                pw.println("Package warning messages:");
21586                dumpCriticalInfo(pw, null);
21587            }
21588
21589            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21590                dumpCriticalInfo(pw, "msg,");
21591            }
21592        }
21593
21594        // PackageInstaller should be called outside of mPackages lock
21595        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21596            // XXX should handle packageName != null by dumping only install data that
21597            // the given package is involved with.
21598            if (dumpState.onTitlePrinted()) pw.println();
21599            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21600        }
21601    }
21602
21603    private void dumpProto(FileDescriptor fd) {
21604        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21605
21606        synchronized (mPackages) {
21607            final long requiredVerifierPackageToken =
21608                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21609            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21610            proto.write(
21611                    PackageServiceDumpProto.PackageShortProto.UID,
21612                    getPackageUid(
21613                            mRequiredVerifierPackage,
21614                            MATCH_DEBUG_TRIAGED_MISSING,
21615                            UserHandle.USER_SYSTEM));
21616            proto.end(requiredVerifierPackageToken);
21617
21618            if (mIntentFilterVerifierComponent != null) {
21619                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21620                final long verifierPackageToken =
21621                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21622                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21623                proto.write(
21624                        PackageServiceDumpProto.PackageShortProto.UID,
21625                        getPackageUid(
21626                                verifierPackageName,
21627                                MATCH_DEBUG_TRIAGED_MISSING,
21628                                UserHandle.USER_SYSTEM));
21629                proto.end(verifierPackageToken);
21630            }
21631
21632            dumpSharedLibrariesProto(proto);
21633            dumpFeaturesProto(proto);
21634            mSettings.dumpPackagesProto(proto);
21635            mSettings.dumpSharedUsersProto(proto);
21636            dumpCriticalInfo(proto);
21637        }
21638        proto.flush();
21639    }
21640
21641    private void dumpFeaturesProto(ProtoOutputStream proto) {
21642        synchronized (mAvailableFeatures) {
21643            final int count = mAvailableFeatures.size();
21644            for (int i = 0; i < count; i++) {
21645                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21646            }
21647        }
21648    }
21649
21650    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21651        final int count = mSharedLibraries.size();
21652        for (int i = 0; i < count; i++) {
21653            final String libName = mSharedLibraries.keyAt(i);
21654            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21655            if (versionedLib == null) {
21656                continue;
21657            }
21658            final int versionCount = versionedLib.size();
21659            for (int j = 0; j < versionCount; j++) {
21660                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21661                final long sharedLibraryToken =
21662                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21663                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21664                final boolean isJar = (libEntry.path != null);
21665                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21666                if (isJar) {
21667                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21668                } else {
21669                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21670                }
21671                proto.end(sharedLibraryToken);
21672            }
21673        }
21674    }
21675
21676    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21677        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21678        ipw.println();
21679        ipw.println("Dexopt state:");
21680        ipw.increaseIndent();
21681        Collection<PackageParser.Package> packages = null;
21682        if (packageName != null) {
21683            PackageParser.Package targetPackage = mPackages.get(packageName);
21684            if (targetPackage != null) {
21685                packages = Collections.singletonList(targetPackage);
21686            } else {
21687                ipw.println("Unable to find package: " + packageName);
21688                return;
21689            }
21690        } else {
21691            packages = mPackages.values();
21692        }
21693
21694        for (PackageParser.Package pkg : packages) {
21695            ipw.println("[" + pkg.packageName + "]");
21696            ipw.increaseIndent();
21697            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21698                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21699            ipw.decreaseIndent();
21700        }
21701    }
21702
21703    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21704        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21705        ipw.println();
21706        ipw.println("Compiler stats:");
21707        ipw.increaseIndent();
21708        Collection<PackageParser.Package> packages = null;
21709        if (packageName != null) {
21710            PackageParser.Package targetPackage = mPackages.get(packageName);
21711            if (targetPackage != null) {
21712                packages = Collections.singletonList(targetPackage);
21713            } else {
21714                ipw.println("Unable to find package: " + packageName);
21715                return;
21716            }
21717        } else {
21718            packages = mPackages.values();
21719        }
21720
21721        for (PackageParser.Package pkg : packages) {
21722            ipw.println("[" + pkg.packageName + "]");
21723            ipw.increaseIndent();
21724
21725            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21726            if (stats == null) {
21727                ipw.println("(No recorded stats)");
21728            } else {
21729                stats.dump(ipw);
21730            }
21731            ipw.decreaseIndent();
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.
22311        mArtManagerService.prepareAppProfiles(pkg, userId);
22312
22313        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22314            // TODO: mark this structure as dirty so we persist it!
22315            synchronized (mPackages) {
22316                final PackageSetting ps = mSettings.mPackages.get(packageName);
22317                if (ps != null) {
22318                    ps.setCeDataInode(ceDataInode, userId);
22319                }
22320            }
22321        }
22322
22323        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22324    }
22325
22326    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22327        if (pkg == null) {
22328            Slog.wtf(TAG, "Package was null!", new Throwable());
22329            return;
22330        }
22331        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22332        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22333        for (int i = 0; i < childCount; i++) {
22334            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22335        }
22336    }
22337
22338    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22339        final String volumeUuid = pkg.volumeUuid;
22340        final String packageName = pkg.packageName;
22341        final ApplicationInfo app = pkg.applicationInfo;
22342
22343        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22344            // Create a native library symlink only if we have native libraries
22345            // and if the native libraries are 32 bit libraries. We do not provide
22346            // this symlink for 64 bit libraries.
22347            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22348                final String nativeLibPath = app.nativeLibraryDir;
22349                try {
22350                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22351                            nativeLibPath, userId);
22352                } catch (InstallerException e) {
22353                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22354                }
22355            }
22356        }
22357    }
22358
22359    /**
22360     * For system apps on non-FBE devices, this method migrates any existing
22361     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22362     * requested by the app.
22363     */
22364    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22365        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22366                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22367            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22368                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22369            try {
22370                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22371                        storageTarget);
22372            } catch (InstallerException e) {
22373                logCriticalInfo(Log.WARN,
22374                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22375            }
22376            return true;
22377        } else {
22378            return false;
22379        }
22380    }
22381
22382    public PackageFreezer freezePackage(String packageName, String killReason) {
22383        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22384    }
22385
22386    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22387        return new PackageFreezer(packageName, userId, killReason);
22388    }
22389
22390    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22391            String killReason) {
22392        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22393    }
22394
22395    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22396            String killReason) {
22397        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22398            return new PackageFreezer();
22399        } else {
22400            return freezePackage(packageName, userId, killReason);
22401        }
22402    }
22403
22404    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22405            String killReason) {
22406        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22407    }
22408
22409    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22410            String killReason) {
22411        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22412            return new PackageFreezer();
22413        } else {
22414            return freezePackage(packageName, userId, killReason);
22415        }
22416    }
22417
22418    /**
22419     * Class that freezes and kills the given package upon creation, and
22420     * unfreezes it upon closing. This is typically used when doing surgery on
22421     * app code/data to prevent the app from running while you're working.
22422     */
22423    private class PackageFreezer implements AutoCloseable {
22424        private final String mPackageName;
22425        private final PackageFreezer[] mChildren;
22426
22427        private final boolean mWeFroze;
22428
22429        private final AtomicBoolean mClosed = new AtomicBoolean();
22430        private final CloseGuard mCloseGuard = CloseGuard.get();
22431
22432        /**
22433         * Create and return a stub freezer that doesn't actually do anything,
22434         * typically used when someone requested
22435         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22436         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22437         */
22438        public PackageFreezer() {
22439            mPackageName = null;
22440            mChildren = null;
22441            mWeFroze = false;
22442            mCloseGuard.open("close");
22443        }
22444
22445        public PackageFreezer(String packageName, int userId, String killReason) {
22446            synchronized (mPackages) {
22447                mPackageName = packageName;
22448                mWeFroze = mFrozenPackages.add(mPackageName);
22449
22450                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22451                if (ps != null) {
22452                    killApplication(ps.name, ps.appId, userId, killReason);
22453                }
22454
22455                final PackageParser.Package p = mPackages.get(packageName);
22456                if (p != null && p.childPackages != null) {
22457                    final int N = p.childPackages.size();
22458                    mChildren = new PackageFreezer[N];
22459                    for (int i = 0; i < N; i++) {
22460                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22461                                userId, killReason);
22462                    }
22463                } else {
22464                    mChildren = null;
22465                }
22466            }
22467            mCloseGuard.open("close");
22468        }
22469
22470        @Override
22471        protected void finalize() throws Throwable {
22472            try {
22473                if (mCloseGuard != null) {
22474                    mCloseGuard.warnIfOpen();
22475                }
22476
22477                close();
22478            } finally {
22479                super.finalize();
22480            }
22481        }
22482
22483        @Override
22484        public void close() {
22485            mCloseGuard.close();
22486            if (mClosed.compareAndSet(false, true)) {
22487                synchronized (mPackages) {
22488                    if (mWeFroze) {
22489                        mFrozenPackages.remove(mPackageName);
22490                    }
22491
22492                    if (mChildren != null) {
22493                        for (PackageFreezer freezer : mChildren) {
22494                            freezer.close();
22495                        }
22496                    }
22497                }
22498            }
22499        }
22500    }
22501
22502    /**
22503     * Verify that given package is currently frozen.
22504     */
22505    private void checkPackageFrozen(String packageName) {
22506        synchronized (mPackages) {
22507            if (!mFrozenPackages.contains(packageName)) {
22508                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22509            }
22510        }
22511    }
22512
22513    @Override
22514    public int movePackage(final String packageName, final String volumeUuid) {
22515        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22516
22517        final int callingUid = Binder.getCallingUid();
22518        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22519        final int moveId = mNextMoveId.getAndIncrement();
22520        mHandler.post(new Runnable() {
22521            @Override
22522            public void run() {
22523                try {
22524                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22525                } catch (PackageManagerException e) {
22526                    Slog.w(TAG, "Failed to move " + packageName, e);
22527                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22528                }
22529            }
22530        });
22531        return moveId;
22532    }
22533
22534    private void movePackageInternal(final String packageName, final String volumeUuid,
22535            final int moveId, final int callingUid, UserHandle user)
22536                    throws PackageManagerException {
22537        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22538        final PackageManager pm = mContext.getPackageManager();
22539
22540        final boolean currentAsec;
22541        final String currentVolumeUuid;
22542        final File codeFile;
22543        final String installerPackageName;
22544        final String packageAbiOverride;
22545        final int appId;
22546        final String seinfo;
22547        final String label;
22548        final int targetSdkVersion;
22549        final PackageFreezer freezer;
22550        final int[] installedUserIds;
22551
22552        // reader
22553        synchronized (mPackages) {
22554            final PackageParser.Package pkg = mPackages.get(packageName);
22555            final PackageSetting ps = mSettings.mPackages.get(packageName);
22556            if (pkg == null
22557                    || ps == null
22558                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22559                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22560            }
22561            if (pkg.applicationInfo.isSystemApp()) {
22562                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22563                        "Cannot move system application");
22564            }
22565
22566            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22567            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22568                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22569            if (isInternalStorage && !allow3rdPartyOnInternal) {
22570                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22571                        "3rd party apps are not allowed on internal storage");
22572            }
22573
22574            if (pkg.applicationInfo.isExternalAsec()) {
22575                currentAsec = true;
22576                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22577            } else if (pkg.applicationInfo.isForwardLocked()) {
22578                currentAsec = true;
22579                currentVolumeUuid = "forward_locked";
22580            } else {
22581                currentAsec = false;
22582                currentVolumeUuid = ps.volumeUuid;
22583
22584                final File probe = new File(pkg.codePath);
22585                final File probeOat = new File(probe, "oat");
22586                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22587                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22588                            "Move only supported for modern cluster style installs");
22589                }
22590            }
22591
22592            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22593                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22594                        "Package already moved to " + volumeUuid);
22595            }
22596            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22597                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22598                        "Device admin cannot be moved");
22599            }
22600
22601            if (mFrozenPackages.contains(packageName)) {
22602                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22603                        "Failed to move already frozen package");
22604            }
22605
22606            codeFile = new File(pkg.codePath);
22607            installerPackageName = ps.installerPackageName;
22608            packageAbiOverride = ps.cpuAbiOverrideString;
22609            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22610            seinfo = pkg.applicationInfo.seInfo;
22611            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22612            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22613            freezer = freezePackage(packageName, "movePackageInternal");
22614            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22615        }
22616
22617        final Bundle extras = new Bundle();
22618        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22619        extras.putString(Intent.EXTRA_TITLE, label);
22620        mMoveCallbacks.notifyCreated(moveId, extras);
22621
22622        int installFlags;
22623        final boolean moveCompleteApp;
22624        final File measurePath;
22625
22626        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22627            installFlags = INSTALL_INTERNAL;
22628            moveCompleteApp = !currentAsec;
22629            measurePath = Environment.getDataAppDirectory(volumeUuid);
22630        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22631            installFlags = INSTALL_EXTERNAL;
22632            moveCompleteApp = false;
22633            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22634        } else {
22635            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22636            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22637                    || !volume.isMountedWritable()) {
22638                freezer.close();
22639                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22640                        "Move location not mounted private volume");
22641            }
22642
22643            Preconditions.checkState(!currentAsec);
22644
22645            installFlags = INSTALL_INTERNAL;
22646            moveCompleteApp = true;
22647            measurePath = Environment.getDataAppDirectory(volumeUuid);
22648        }
22649
22650        // If we're moving app data around, we need all the users unlocked
22651        if (moveCompleteApp) {
22652            for (int userId : installedUserIds) {
22653                if (StorageManager.isFileEncryptedNativeOrEmulated()
22654                        && !StorageManager.isUserKeyUnlocked(userId)) {
22655                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22656                            "User " + userId + " must be unlocked");
22657                }
22658            }
22659        }
22660
22661        final PackageStats stats = new PackageStats(null, -1);
22662        synchronized (mInstaller) {
22663            for (int userId : installedUserIds) {
22664                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22665                    freezer.close();
22666                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22667                            "Failed to measure package size");
22668                }
22669            }
22670        }
22671
22672        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22673                + stats.dataSize);
22674
22675        final long startFreeBytes = measurePath.getUsableSpace();
22676        final long sizeBytes;
22677        if (moveCompleteApp) {
22678            sizeBytes = stats.codeSize + stats.dataSize;
22679        } else {
22680            sizeBytes = stats.codeSize;
22681        }
22682
22683        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22684            freezer.close();
22685            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22686                    "Not enough free space to move");
22687        }
22688
22689        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22690
22691        final CountDownLatch installedLatch = new CountDownLatch(1);
22692        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22693            @Override
22694            public void onUserActionRequired(Intent intent) throws RemoteException {
22695                throw new IllegalStateException();
22696            }
22697
22698            @Override
22699            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22700                    Bundle extras) throws RemoteException {
22701                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22702                        + PackageManager.installStatusToString(returnCode, msg));
22703
22704                installedLatch.countDown();
22705                freezer.close();
22706
22707                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22708                switch (status) {
22709                    case PackageInstaller.STATUS_SUCCESS:
22710                        mMoveCallbacks.notifyStatusChanged(moveId,
22711                                PackageManager.MOVE_SUCCEEDED);
22712                        break;
22713                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22714                        mMoveCallbacks.notifyStatusChanged(moveId,
22715                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22716                        break;
22717                    default:
22718                        mMoveCallbacks.notifyStatusChanged(moveId,
22719                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22720                        break;
22721                }
22722            }
22723        };
22724
22725        final MoveInfo move;
22726        if (moveCompleteApp) {
22727            // Kick off a thread to report progress estimates
22728            new Thread() {
22729                @Override
22730                public void run() {
22731                    while (true) {
22732                        try {
22733                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22734                                break;
22735                            }
22736                        } catch (InterruptedException ignored) {
22737                        }
22738
22739                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22740                        final int progress = 10 + (int) MathUtils.constrain(
22741                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22742                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22743                    }
22744                }
22745            }.start();
22746
22747            final String dataAppName = codeFile.getName();
22748            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22749                    dataAppName, appId, seinfo, targetSdkVersion);
22750        } else {
22751            move = null;
22752        }
22753
22754        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22755
22756        final Message msg = mHandler.obtainMessage(INIT_COPY);
22757        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22758        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22759                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22760                packageAbiOverride, null /*grantedPermissions*/,
22761                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22762        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22763        msg.obj = params;
22764
22765        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22766                System.identityHashCode(msg.obj));
22767        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22768                System.identityHashCode(msg.obj));
22769
22770        mHandler.sendMessage(msg);
22771    }
22772
22773    @Override
22774    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22775        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22776
22777        final int realMoveId = mNextMoveId.getAndIncrement();
22778        final Bundle extras = new Bundle();
22779        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22780        mMoveCallbacks.notifyCreated(realMoveId, extras);
22781
22782        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22783            @Override
22784            public void onCreated(int moveId, Bundle extras) {
22785                // Ignored
22786            }
22787
22788            @Override
22789            public void onStatusChanged(int moveId, int status, long estMillis) {
22790                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22791            }
22792        };
22793
22794        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22795        storage.setPrimaryStorageUuid(volumeUuid, callback);
22796        return realMoveId;
22797    }
22798
22799    @Override
22800    public int getMoveStatus(int moveId) {
22801        mContext.enforceCallingOrSelfPermission(
22802                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22803        return mMoveCallbacks.mLastStatus.get(moveId);
22804    }
22805
22806    @Override
22807    public void registerMoveCallback(IPackageMoveObserver callback) {
22808        mContext.enforceCallingOrSelfPermission(
22809                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22810        mMoveCallbacks.register(callback);
22811    }
22812
22813    @Override
22814    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22815        mContext.enforceCallingOrSelfPermission(
22816                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22817        mMoveCallbacks.unregister(callback);
22818    }
22819
22820    @Override
22821    public boolean setInstallLocation(int loc) {
22822        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22823                null);
22824        if (getInstallLocation() == loc) {
22825            return true;
22826        }
22827        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22828                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22829            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22830                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22831            return true;
22832        }
22833        return false;
22834   }
22835
22836    @Override
22837    public int getInstallLocation() {
22838        // allow instant app access
22839        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22840                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22841                PackageHelper.APP_INSTALL_AUTO);
22842    }
22843
22844    /** Called by UserManagerService */
22845    void cleanUpUser(UserManagerService userManager, int userHandle) {
22846        synchronized (mPackages) {
22847            mDirtyUsers.remove(userHandle);
22848            mUserNeedsBadging.delete(userHandle);
22849            mSettings.removeUserLPw(userHandle);
22850            mPendingBroadcasts.remove(userHandle);
22851            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22852            removeUnusedPackagesLPw(userManager, userHandle);
22853        }
22854    }
22855
22856    /**
22857     * We're removing userHandle and would like to remove any downloaded packages
22858     * that are no longer in use by any other user.
22859     * @param userHandle the user being removed
22860     */
22861    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22862        final boolean DEBUG_CLEAN_APKS = false;
22863        int [] users = userManager.getUserIds();
22864        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22865        while (psit.hasNext()) {
22866            PackageSetting ps = psit.next();
22867            if (ps.pkg == null) {
22868                continue;
22869            }
22870            final String packageName = ps.pkg.packageName;
22871            // Skip over if system app
22872            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22873                continue;
22874            }
22875            if (DEBUG_CLEAN_APKS) {
22876                Slog.i(TAG, "Checking package " + packageName);
22877            }
22878            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22879            if (keep) {
22880                if (DEBUG_CLEAN_APKS) {
22881                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22882                }
22883            } else {
22884                for (int i = 0; i < users.length; i++) {
22885                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22886                        keep = true;
22887                        if (DEBUG_CLEAN_APKS) {
22888                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22889                                    + users[i]);
22890                        }
22891                        break;
22892                    }
22893                }
22894            }
22895            if (!keep) {
22896                if (DEBUG_CLEAN_APKS) {
22897                    Slog.i(TAG, "  Removing package " + packageName);
22898                }
22899                mHandler.post(new Runnable() {
22900                    public void run() {
22901                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22902                                userHandle, 0);
22903                    } //end run
22904                });
22905            }
22906        }
22907    }
22908
22909    /** Called by UserManagerService */
22910    void createNewUser(int userId, String[] disallowedPackages) {
22911        synchronized (mInstallLock) {
22912            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22913        }
22914        synchronized (mPackages) {
22915            scheduleWritePackageRestrictionsLocked(userId);
22916            scheduleWritePackageListLocked(userId);
22917            applyFactoryDefaultBrowserLPw(userId);
22918            primeDomainVerificationsLPw(userId);
22919        }
22920    }
22921
22922    void onNewUserCreated(final int userId) {
22923        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22924        synchronized(mPackages) {
22925            // If permission review for legacy apps is required, we represent
22926            // dagerous permissions for such apps as always granted runtime
22927            // permissions to keep per user flag state whether review is needed.
22928            // Hence, if a new user is added we have to propagate dangerous
22929            // permission grants for these legacy apps.
22930            if (mSettings.mPermissions.mPermissionReviewRequired) {
22931// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22932                mPermissionManager.updateAllPermissions(
22933                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22934                        mPermissionCallback);
22935            }
22936        }
22937    }
22938
22939    @Override
22940    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22941        mContext.enforceCallingOrSelfPermission(
22942                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22943                "Only package verification agents can read the verifier device identity");
22944
22945        synchronized (mPackages) {
22946            return mSettings.getVerifierDeviceIdentityLPw();
22947        }
22948    }
22949
22950    @Override
22951    public void setPermissionEnforced(String permission, boolean enforced) {
22952        // TODO: Now that we no longer change GID for storage, this should to away.
22953        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22954                "setPermissionEnforced");
22955        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22956            synchronized (mPackages) {
22957                if (mSettings.mReadExternalStorageEnforced == null
22958                        || mSettings.mReadExternalStorageEnforced != enforced) {
22959                    mSettings.mReadExternalStorageEnforced =
22960                            enforced ? Boolean.TRUE : Boolean.FALSE;
22961                    mSettings.writeLPr();
22962                }
22963            }
22964            // kill any non-foreground processes so we restart them and
22965            // grant/revoke the GID.
22966            final IActivityManager am = ActivityManager.getService();
22967            if (am != null) {
22968                final long token = Binder.clearCallingIdentity();
22969                try {
22970                    am.killProcessesBelowForeground("setPermissionEnforcement");
22971                } catch (RemoteException e) {
22972                } finally {
22973                    Binder.restoreCallingIdentity(token);
22974                }
22975            }
22976        } else {
22977            throw new IllegalArgumentException("No selective enforcement for " + permission);
22978        }
22979    }
22980
22981    @Override
22982    @Deprecated
22983    public boolean isPermissionEnforced(String permission) {
22984        // allow instant applications
22985        return true;
22986    }
22987
22988    @Override
22989    public boolean isStorageLow() {
22990        // allow instant applications
22991        final long token = Binder.clearCallingIdentity();
22992        try {
22993            final DeviceStorageMonitorInternal
22994                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22995            if (dsm != null) {
22996                return dsm.isMemoryLow();
22997            } else {
22998                return false;
22999            }
23000        } finally {
23001            Binder.restoreCallingIdentity(token);
23002        }
23003    }
23004
23005    @Override
23006    public IPackageInstaller getPackageInstaller() {
23007        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23008            return null;
23009        }
23010        return mInstallerService;
23011    }
23012
23013    @Override
23014    public IArtManager getArtManager() {
23015        return mArtManagerService;
23016    }
23017
23018    private boolean userNeedsBadging(int userId) {
23019        int index = mUserNeedsBadging.indexOfKey(userId);
23020        if (index < 0) {
23021            final UserInfo userInfo;
23022            final long token = Binder.clearCallingIdentity();
23023            try {
23024                userInfo = sUserManager.getUserInfo(userId);
23025            } finally {
23026                Binder.restoreCallingIdentity(token);
23027            }
23028            final boolean b;
23029            if (userInfo != null && userInfo.isManagedProfile()) {
23030                b = true;
23031            } else {
23032                b = false;
23033            }
23034            mUserNeedsBadging.put(userId, b);
23035            return b;
23036        }
23037        return mUserNeedsBadging.valueAt(index);
23038    }
23039
23040    @Override
23041    public KeySet getKeySetByAlias(String packageName, String alias) {
23042        if (packageName == null || alias == null) {
23043            return null;
23044        }
23045        synchronized(mPackages) {
23046            final PackageParser.Package pkg = mPackages.get(packageName);
23047            if (pkg == null) {
23048                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23049                throw new IllegalArgumentException("Unknown package: " + packageName);
23050            }
23051            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23052            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23053                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23054                throw new IllegalArgumentException("Unknown package: " + packageName);
23055            }
23056            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23057            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23058        }
23059    }
23060
23061    @Override
23062    public KeySet getSigningKeySet(String packageName) {
23063        if (packageName == null) {
23064            return null;
23065        }
23066        synchronized(mPackages) {
23067            final int callingUid = Binder.getCallingUid();
23068            final int callingUserId = UserHandle.getUserId(callingUid);
23069            final PackageParser.Package pkg = mPackages.get(packageName);
23070            if (pkg == null) {
23071                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23072                throw new IllegalArgumentException("Unknown package: " + packageName);
23073            }
23074            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23075            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23076                // filter and pretend the package doesn't exist
23077                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23078                        + ", uid:" + callingUid);
23079                throw new IllegalArgumentException("Unknown package: " + packageName);
23080            }
23081            if (pkg.applicationInfo.uid != callingUid
23082                    && Process.SYSTEM_UID != callingUid) {
23083                throw new SecurityException("May not access signing KeySet of other apps.");
23084            }
23085            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23086            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23087        }
23088    }
23089
23090    @Override
23091    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23092        final int callingUid = Binder.getCallingUid();
23093        if (getInstantAppPackageName(callingUid) != null) {
23094            return false;
23095        }
23096        if (packageName == null || ks == null) {
23097            return false;
23098        }
23099        synchronized(mPackages) {
23100            final PackageParser.Package pkg = mPackages.get(packageName);
23101            if (pkg == null
23102                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23103                            UserHandle.getUserId(callingUid))) {
23104                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23105                throw new IllegalArgumentException("Unknown package: " + packageName);
23106            }
23107            IBinder ksh = ks.getToken();
23108            if (ksh instanceof KeySetHandle) {
23109                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23110                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23111            }
23112            return false;
23113        }
23114    }
23115
23116    @Override
23117    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23118        final int callingUid = Binder.getCallingUid();
23119        if (getInstantAppPackageName(callingUid) != null) {
23120            return false;
23121        }
23122        if (packageName == null || ks == null) {
23123            return false;
23124        }
23125        synchronized(mPackages) {
23126            final PackageParser.Package pkg = mPackages.get(packageName);
23127            if (pkg == null
23128                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23129                            UserHandle.getUserId(callingUid))) {
23130                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23131                throw new IllegalArgumentException("Unknown package: " + packageName);
23132            }
23133            IBinder ksh = ks.getToken();
23134            if (ksh instanceof KeySetHandle) {
23135                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23136                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23137            }
23138            return false;
23139        }
23140    }
23141
23142    private void deletePackageIfUnusedLPr(final String packageName) {
23143        PackageSetting ps = mSettings.mPackages.get(packageName);
23144        if (ps == null) {
23145            return;
23146        }
23147        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23148            // TODO Implement atomic delete if package is unused
23149            // It is currently possible that the package will be deleted even if it is installed
23150            // after this method returns.
23151            mHandler.post(new Runnable() {
23152                public void run() {
23153                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23154                            0, PackageManager.DELETE_ALL_USERS);
23155                }
23156            });
23157        }
23158    }
23159
23160    /**
23161     * Check and throw if the given before/after packages would be considered a
23162     * downgrade.
23163     */
23164    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23165            throws PackageManagerException {
23166        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23167            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23168                    "Update version code " + after.versionCode + " is older than current "
23169                    + before.getLongVersionCode());
23170        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23171            if (after.baseRevisionCode < before.baseRevisionCode) {
23172                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23173                        "Update base revision code " + after.baseRevisionCode
23174                        + " is older than current " + before.baseRevisionCode);
23175            }
23176
23177            if (!ArrayUtils.isEmpty(after.splitNames)) {
23178                for (int i = 0; i < after.splitNames.length; i++) {
23179                    final String splitName = after.splitNames[i];
23180                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23181                    if (j != -1) {
23182                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23183                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23184                                    "Update split " + splitName + " revision code "
23185                                    + after.splitRevisionCodes[i] + " is older than current "
23186                                    + before.splitRevisionCodes[j]);
23187                        }
23188                    }
23189                }
23190            }
23191        }
23192    }
23193
23194    private static class MoveCallbacks extends Handler {
23195        private static final int MSG_CREATED = 1;
23196        private static final int MSG_STATUS_CHANGED = 2;
23197
23198        private final RemoteCallbackList<IPackageMoveObserver>
23199                mCallbacks = new RemoteCallbackList<>();
23200
23201        private final SparseIntArray mLastStatus = new SparseIntArray();
23202
23203        public MoveCallbacks(Looper looper) {
23204            super(looper);
23205        }
23206
23207        public void register(IPackageMoveObserver callback) {
23208            mCallbacks.register(callback);
23209        }
23210
23211        public void unregister(IPackageMoveObserver callback) {
23212            mCallbacks.unregister(callback);
23213        }
23214
23215        @Override
23216        public void handleMessage(Message msg) {
23217            final SomeArgs args = (SomeArgs) msg.obj;
23218            final int n = mCallbacks.beginBroadcast();
23219            for (int i = 0; i < n; i++) {
23220                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23221                try {
23222                    invokeCallback(callback, msg.what, args);
23223                } catch (RemoteException ignored) {
23224                }
23225            }
23226            mCallbacks.finishBroadcast();
23227            args.recycle();
23228        }
23229
23230        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23231                throws RemoteException {
23232            switch (what) {
23233                case MSG_CREATED: {
23234                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23235                    break;
23236                }
23237                case MSG_STATUS_CHANGED: {
23238                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23239                    break;
23240                }
23241            }
23242        }
23243
23244        private void notifyCreated(int moveId, Bundle extras) {
23245            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23246
23247            final SomeArgs args = SomeArgs.obtain();
23248            args.argi1 = moveId;
23249            args.arg2 = extras;
23250            obtainMessage(MSG_CREATED, args).sendToTarget();
23251        }
23252
23253        private void notifyStatusChanged(int moveId, int status) {
23254            notifyStatusChanged(moveId, status, -1);
23255        }
23256
23257        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23258            Slog.v(TAG, "Move " + moveId + " status " + status);
23259
23260            final SomeArgs args = SomeArgs.obtain();
23261            args.argi1 = moveId;
23262            args.argi2 = status;
23263            args.arg3 = estMillis;
23264            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23265
23266            synchronized (mLastStatus) {
23267                mLastStatus.put(moveId, status);
23268            }
23269        }
23270    }
23271
23272    private final static class OnPermissionChangeListeners extends Handler {
23273        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23274
23275        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23276                new RemoteCallbackList<>();
23277
23278        public OnPermissionChangeListeners(Looper looper) {
23279            super(looper);
23280        }
23281
23282        @Override
23283        public void handleMessage(Message msg) {
23284            switch (msg.what) {
23285                case MSG_ON_PERMISSIONS_CHANGED: {
23286                    final int uid = msg.arg1;
23287                    handleOnPermissionsChanged(uid);
23288                } break;
23289            }
23290        }
23291
23292        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23293            mPermissionListeners.register(listener);
23294
23295        }
23296
23297        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23298            mPermissionListeners.unregister(listener);
23299        }
23300
23301        public void onPermissionsChanged(int uid) {
23302            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23303                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23304            }
23305        }
23306
23307        private void handleOnPermissionsChanged(int uid) {
23308            final int count = mPermissionListeners.beginBroadcast();
23309            try {
23310                for (int i = 0; i < count; i++) {
23311                    IOnPermissionsChangeListener callback = mPermissionListeners
23312                            .getBroadcastItem(i);
23313                    try {
23314                        callback.onPermissionsChanged(uid);
23315                    } catch (RemoteException e) {
23316                        Log.e(TAG, "Permission listener is dead", e);
23317                    }
23318                }
23319            } finally {
23320                mPermissionListeners.finishBroadcast();
23321            }
23322        }
23323    }
23324
23325    private class PackageManagerNative extends IPackageManagerNative.Stub {
23326        @Override
23327        public String[] getNamesForUids(int[] uids) throws RemoteException {
23328            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23329            // massage results so they can be parsed by the native binder
23330            for (int i = results.length - 1; i >= 0; --i) {
23331                if (results[i] == null) {
23332                    results[i] = "";
23333                }
23334            }
23335            return results;
23336        }
23337
23338        // NB: this differentiates between preloads and sideloads
23339        @Override
23340        public String getInstallerForPackage(String packageName) throws RemoteException {
23341            final String installerName = getInstallerPackageName(packageName);
23342            if (!TextUtils.isEmpty(installerName)) {
23343                return installerName;
23344            }
23345            // differentiate between preload and sideload
23346            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23347            ApplicationInfo appInfo = getApplicationInfo(packageName,
23348                                    /*flags*/ 0,
23349                                    /*userId*/ callingUser);
23350            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23351                return "preload";
23352            }
23353            return "";
23354        }
23355
23356        @Override
23357        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23358            try {
23359                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23360                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23361                if (pInfo != null) {
23362                    return pInfo.getLongVersionCode();
23363                }
23364            } catch (Exception e) {
23365            }
23366            return 0;
23367        }
23368    }
23369
23370    private class PackageManagerInternalImpl extends PackageManagerInternal {
23371        @Override
23372        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23373                int flagValues, int userId) {
23374            PackageManagerService.this.updatePermissionFlags(
23375                    permName, packageName, flagMask, flagValues, userId);
23376        }
23377
23378        @Override
23379        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23380            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23381        }
23382
23383        @Override
23384        public boolean isInstantApp(String packageName, int userId) {
23385            return PackageManagerService.this.isInstantApp(packageName, userId);
23386        }
23387
23388        @Override
23389        public String getInstantAppPackageName(int uid) {
23390            return PackageManagerService.this.getInstantAppPackageName(uid);
23391        }
23392
23393        @Override
23394        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23395            synchronized (mPackages) {
23396                return PackageManagerService.this.filterAppAccessLPr(
23397                        (PackageSetting) pkg.mExtras, callingUid, userId);
23398            }
23399        }
23400
23401        @Override
23402        public PackageParser.Package getPackage(String packageName) {
23403            synchronized (mPackages) {
23404                packageName = resolveInternalPackageNameLPr(
23405                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23406                return mPackages.get(packageName);
23407            }
23408        }
23409
23410        @Override
23411        public PackageList getPackageList(PackageListObserver observer) {
23412            synchronized (mPackages) {
23413                final int N = mPackages.size();
23414                final ArrayList<String> list = new ArrayList<>(N);
23415                for (int i = 0; i < N; i++) {
23416                    list.add(mPackages.keyAt(i));
23417                }
23418                final PackageList packageList = new PackageList(list, observer);
23419                if (observer != null) {
23420                    mPackageListObservers.add(packageList);
23421                }
23422                return packageList;
23423            }
23424        }
23425
23426        @Override
23427        public void removePackageListObserver(PackageListObserver observer) {
23428            synchronized (mPackages) {
23429                mPackageListObservers.remove(observer);
23430            }
23431        }
23432
23433        @Override
23434        public PackageParser.Package getDisabledPackage(String packageName) {
23435            synchronized (mPackages) {
23436                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23437                return (ps != null) ? ps.pkg : null;
23438            }
23439        }
23440
23441        @Override
23442        public String getKnownPackageName(int knownPackage, int userId) {
23443            switch(knownPackage) {
23444                case PackageManagerInternal.PACKAGE_BROWSER:
23445                    return getDefaultBrowserPackageName(userId);
23446                case PackageManagerInternal.PACKAGE_INSTALLER:
23447                    return mRequiredInstallerPackage;
23448                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23449                    return mSetupWizardPackage;
23450                case PackageManagerInternal.PACKAGE_SYSTEM:
23451                    return "android";
23452                case PackageManagerInternal.PACKAGE_VERIFIER:
23453                    return mRequiredVerifierPackage;
23454            }
23455            return null;
23456        }
23457
23458        @Override
23459        public boolean isResolveActivityComponent(ComponentInfo component) {
23460            return mResolveActivity.packageName.equals(component.packageName)
23461                    && mResolveActivity.name.equals(component.name);
23462        }
23463
23464        @Override
23465        public void setLocationPackagesProvider(PackagesProvider provider) {
23466            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23467        }
23468
23469        @Override
23470        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23471            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23472        }
23473
23474        @Override
23475        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23476            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23477        }
23478
23479        @Override
23480        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23481            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23482        }
23483
23484        @Override
23485        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23486            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23487        }
23488
23489        @Override
23490        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23491            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23492        }
23493
23494        @Override
23495        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23496            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23497        }
23498
23499        @Override
23500        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23501            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23502        }
23503
23504        @Override
23505        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23506            synchronized (mPackages) {
23507                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23508            }
23509            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23510        }
23511
23512        @Override
23513        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23514            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23515                    packageName, userId);
23516        }
23517
23518        @Override
23519        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23520            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23521                    packageName, userId);
23522        }
23523
23524        @Override
23525        public void setKeepUninstalledPackages(final List<String> packageList) {
23526            Preconditions.checkNotNull(packageList);
23527            List<String> removedFromList = null;
23528            synchronized (mPackages) {
23529                if (mKeepUninstalledPackages != null) {
23530                    final int packagesCount = mKeepUninstalledPackages.size();
23531                    for (int i = 0; i < packagesCount; i++) {
23532                        String oldPackage = mKeepUninstalledPackages.get(i);
23533                        if (packageList != null && packageList.contains(oldPackage)) {
23534                            continue;
23535                        }
23536                        if (removedFromList == null) {
23537                            removedFromList = new ArrayList<>();
23538                        }
23539                        removedFromList.add(oldPackage);
23540                    }
23541                }
23542                mKeepUninstalledPackages = new ArrayList<>(packageList);
23543                if (removedFromList != null) {
23544                    final int removedCount = removedFromList.size();
23545                    for (int i = 0; i < removedCount; i++) {
23546                        deletePackageIfUnusedLPr(removedFromList.get(i));
23547                    }
23548                }
23549            }
23550        }
23551
23552        @Override
23553        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23554            synchronized (mPackages) {
23555                return mPermissionManager.isPermissionsReviewRequired(
23556                        mPackages.get(packageName), userId);
23557            }
23558        }
23559
23560        @Override
23561        public PackageInfo getPackageInfo(
23562                String packageName, int flags, int filterCallingUid, int userId) {
23563            return PackageManagerService.this
23564                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23565                            flags, filterCallingUid, userId);
23566        }
23567
23568        @Override
23569        public int getPackageUid(String packageName, int flags, int userId) {
23570            return PackageManagerService.this
23571                    .getPackageUid(packageName, flags, userId);
23572        }
23573
23574        @Override
23575        public ApplicationInfo getApplicationInfo(
23576                String packageName, int flags, int filterCallingUid, int userId) {
23577            return PackageManagerService.this
23578                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23579        }
23580
23581        @Override
23582        public ActivityInfo getActivityInfo(
23583                ComponentName component, int flags, int filterCallingUid, int userId) {
23584            return PackageManagerService.this
23585                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23586        }
23587
23588        @Override
23589        public List<ResolveInfo> queryIntentActivities(
23590                Intent intent, int flags, int filterCallingUid, int userId) {
23591            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23592            return PackageManagerService.this
23593                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23594                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23595        }
23596
23597        @Override
23598        public List<ResolveInfo> queryIntentServices(
23599                Intent intent, int flags, int callingUid, int userId) {
23600            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23601            return PackageManagerService.this
23602                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23603                            false);
23604        }
23605
23606        @Override
23607        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23608                int userId) {
23609            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23610        }
23611
23612        @Override
23613        public void setDeviceAndProfileOwnerPackages(
23614                int deviceOwnerUserId, String deviceOwnerPackage,
23615                SparseArray<String> profileOwnerPackages) {
23616            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23617                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23618        }
23619
23620        @Override
23621        public boolean isPackageDataProtected(int userId, String packageName) {
23622            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23623        }
23624
23625        @Override
23626        public boolean isPackageEphemeral(int userId, String packageName) {
23627            synchronized (mPackages) {
23628                final PackageSetting ps = mSettings.mPackages.get(packageName);
23629                return ps != null ? ps.getInstantApp(userId) : false;
23630            }
23631        }
23632
23633        @Override
23634        public boolean wasPackageEverLaunched(String packageName, int userId) {
23635            synchronized (mPackages) {
23636                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23637            }
23638        }
23639
23640        @Override
23641        public void grantRuntimePermission(String packageName, String permName, int userId,
23642                boolean overridePolicy) {
23643            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23644                    permName, packageName, overridePolicy, getCallingUid(), userId,
23645                    mPermissionCallback);
23646        }
23647
23648        @Override
23649        public void revokeRuntimePermission(String packageName, String permName, int userId,
23650                boolean overridePolicy) {
23651            mPermissionManager.revokeRuntimePermission(
23652                    permName, packageName, overridePolicy, getCallingUid(), userId,
23653                    mPermissionCallback);
23654        }
23655
23656        @Override
23657        public String getNameForUid(int uid) {
23658            return PackageManagerService.this.getNameForUid(uid);
23659        }
23660
23661        @Override
23662        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23663                Intent origIntent, String resolvedType, String callingPackage,
23664                Bundle verificationBundle, int userId) {
23665            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23666                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23667                    userId);
23668        }
23669
23670        @Override
23671        public void grantEphemeralAccess(int userId, Intent intent,
23672                int targetAppId, int ephemeralAppId) {
23673            synchronized (mPackages) {
23674                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23675                        targetAppId, ephemeralAppId);
23676            }
23677        }
23678
23679        @Override
23680        public boolean isInstantAppInstallerComponent(ComponentName component) {
23681            synchronized (mPackages) {
23682                return mInstantAppInstallerActivity != null
23683                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23684            }
23685        }
23686
23687        @Override
23688        public void pruneInstantApps() {
23689            mInstantAppRegistry.pruneInstantApps();
23690        }
23691
23692        @Override
23693        public String getSetupWizardPackageName() {
23694            return mSetupWizardPackage;
23695        }
23696
23697        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23698            if (policy != null) {
23699                mExternalSourcesPolicy = policy;
23700            }
23701        }
23702
23703        @Override
23704        public boolean isPackagePersistent(String packageName) {
23705            synchronized (mPackages) {
23706                PackageParser.Package pkg = mPackages.get(packageName);
23707                return pkg != null
23708                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23709                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23710                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23711                        : false;
23712            }
23713        }
23714
23715        @Override
23716        public boolean isLegacySystemApp(Package pkg) {
23717            synchronized (mPackages) {
23718                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23719                return mPromoteSystemApps
23720                        && ps.isSystem()
23721                        && mExistingSystemPackages.contains(ps.name);
23722            }
23723        }
23724
23725        @Override
23726        public List<PackageInfo> getOverlayPackages(int userId) {
23727            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23728            synchronized (mPackages) {
23729                for (PackageParser.Package p : mPackages.values()) {
23730                    if (p.mOverlayTarget != null) {
23731                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23732                        if (pkg != null) {
23733                            overlayPackages.add(pkg);
23734                        }
23735                    }
23736                }
23737            }
23738            return overlayPackages;
23739        }
23740
23741        @Override
23742        public List<String> getTargetPackageNames(int userId) {
23743            List<String> targetPackages = new ArrayList<>();
23744            synchronized (mPackages) {
23745                for (PackageParser.Package p : mPackages.values()) {
23746                    if (p.mOverlayTarget == null) {
23747                        targetPackages.add(p.packageName);
23748                    }
23749                }
23750            }
23751            return targetPackages;
23752        }
23753
23754        @Override
23755        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23756                @Nullable List<String> overlayPackageNames) {
23757            synchronized (mPackages) {
23758                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23759                    Slog.e(TAG, "failed to find package " + targetPackageName);
23760                    return false;
23761                }
23762                ArrayList<String> overlayPaths = null;
23763                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23764                    final int N = overlayPackageNames.size();
23765                    overlayPaths = new ArrayList<>(N);
23766                    for (int i = 0; i < N; i++) {
23767                        final String packageName = overlayPackageNames.get(i);
23768                        final PackageParser.Package pkg = mPackages.get(packageName);
23769                        if (pkg == null) {
23770                            Slog.e(TAG, "failed to find package " + packageName);
23771                            return false;
23772                        }
23773                        overlayPaths.add(pkg.baseCodePath);
23774                    }
23775                }
23776
23777                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23778                ps.setOverlayPaths(overlayPaths, userId);
23779                return true;
23780            }
23781        }
23782
23783        @Override
23784        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23785                int flags, int userId, boolean resolveForStart) {
23786            return resolveIntentInternal(
23787                    intent, resolvedType, flags, userId, resolveForStart);
23788        }
23789
23790        @Override
23791        public ResolveInfo resolveService(Intent intent, String resolvedType,
23792                int flags, int userId, int callingUid) {
23793            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23794        }
23795
23796        @Override
23797        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23798            return PackageManagerService.this.resolveContentProviderInternal(
23799                    name, flags, userId);
23800        }
23801
23802        @Override
23803        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23804            synchronized (mPackages) {
23805                mIsolatedOwners.put(isolatedUid, ownerUid);
23806            }
23807        }
23808
23809        @Override
23810        public void removeIsolatedUid(int isolatedUid) {
23811            synchronized (mPackages) {
23812                mIsolatedOwners.delete(isolatedUid);
23813            }
23814        }
23815
23816        @Override
23817        public int getUidTargetSdkVersion(int uid) {
23818            synchronized (mPackages) {
23819                return getUidTargetSdkVersionLockedLPr(uid);
23820            }
23821        }
23822
23823        @Override
23824        public int getPackageTargetSdkVersion(String packageName) {
23825            synchronized (mPackages) {
23826                return getPackageTargetSdkVersionLockedLPr(packageName);
23827            }
23828        }
23829
23830        @Override
23831        public boolean canAccessInstantApps(int callingUid, int userId) {
23832            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23833        }
23834
23835        @Override
23836        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23837            synchronized (mPackages) {
23838                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23839            }
23840        }
23841
23842        @Override
23843        public void notifyPackageUse(String packageName, int reason) {
23844            synchronized (mPackages) {
23845                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23846            }
23847        }
23848    }
23849
23850    @Override
23851    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23852        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23853        synchronized (mPackages) {
23854            final long identity = Binder.clearCallingIdentity();
23855            try {
23856                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23857                        packageNames, userId);
23858            } finally {
23859                Binder.restoreCallingIdentity(identity);
23860            }
23861        }
23862    }
23863
23864    @Override
23865    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23866        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23867        synchronized (mPackages) {
23868            final long identity = Binder.clearCallingIdentity();
23869            try {
23870                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23871                        packageNames, userId);
23872            } finally {
23873                Binder.restoreCallingIdentity(identity);
23874            }
23875        }
23876    }
23877
23878    private static void enforceSystemOrPhoneCaller(String tag) {
23879        int callingUid = Binder.getCallingUid();
23880        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23881            throw new SecurityException(
23882                    "Cannot call " + tag + " from UID " + callingUid);
23883        }
23884    }
23885
23886    boolean isHistoricalPackageUsageAvailable() {
23887        return mPackageUsage.isHistoricalPackageUsageAvailable();
23888    }
23889
23890    /**
23891     * Return a <b>copy</b> of the collection of packages known to the package manager.
23892     * @return A copy of the values of mPackages.
23893     */
23894    Collection<PackageParser.Package> getPackages() {
23895        synchronized (mPackages) {
23896            return new ArrayList<>(mPackages.values());
23897        }
23898    }
23899
23900    /**
23901     * Logs process start information (including base APK hash) to the security log.
23902     * @hide
23903     */
23904    @Override
23905    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23906            String apkFile, int pid) {
23907        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23908            return;
23909        }
23910        if (!SecurityLog.isLoggingEnabled()) {
23911            return;
23912        }
23913        Bundle data = new Bundle();
23914        data.putLong("startTimestamp", System.currentTimeMillis());
23915        data.putString("processName", processName);
23916        data.putInt("uid", uid);
23917        data.putString("seinfo", seinfo);
23918        data.putString("apkFile", apkFile);
23919        data.putInt("pid", pid);
23920        Message msg = mProcessLoggingHandler.obtainMessage(
23921                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23922        msg.setData(data);
23923        mProcessLoggingHandler.sendMessage(msg);
23924    }
23925
23926    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23927        return mCompilerStats.getPackageStats(pkgName);
23928    }
23929
23930    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23931        return getOrCreateCompilerPackageStats(pkg.packageName);
23932    }
23933
23934    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23935        return mCompilerStats.getOrCreatePackageStats(pkgName);
23936    }
23937
23938    public void deleteCompilerPackageStats(String pkgName) {
23939        mCompilerStats.deletePackageStats(pkgName);
23940    }
23941
23942    @Override
23943    public int getInstallReason(String packageName, int userId) {
23944        final int callingUid = Binder.getCallingUid();
23945        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23946                true /* requireFullPermission */, false /* checkShell */,
23947                "get install reason");
23948        synchronized (mPackages) {
23949            final PackageSetting ps = mSettings.mPackages.get(packageName);
23950            if (filterAppAccessLPr(ps, callingUid, userId)) {
23951                return PackageManager.INSTALL_REASON_UNKNOWN;
23952            }
23953            if (ps != null) {
23954                return ps.getInstallReason(userId);
23955            }
23956        }
23957        return PackageManager.INSTALL_REASON_UNKNOWN;
23958    }
23959
23960    @Override
23961    public boolean canRequestPackageInstalls(String packageName, int userId) {
23962        return canRequestPackageInstallsInternal(packageName, 0, userId,
23963                true /* throwIfPermNotDeclared*/);
23964    }
23965
23966    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23967            boolean throwIfPermNotDeclared) {
23968        int callingUid = Binder.getCallingUid();
23969        int uid = getPackageUid(packageName, 0, userId);
23970        if (callingUid != uid && callingUid != Process.ROOT_UID
23971                && callingUid != Process.SYSTEM_UID) {
23972            throw new SecurityException(
23973                    "Caller uid " + callingUid + " does not own package " + packageName);
23974        }
23975        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23976        if (info == null) {
23977            return false;
23978        }
23979        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23980            return false;
23981        }
23982        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23983        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23984        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23985            if (throwIfPermNotDeclared) {
23986                throw new SecurityException("Need to declare " + appOpPermission
23987                        + " to call this api");
23988            } else {
23989                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23990                return false;
23991            }
23992        }
23993        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23994            return false;
23995        }
23996        if (mExternalSourcesPolicy != null) {
23997            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23998            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23999                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24000            }
24001        }
24002        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24003    }
24004
24005    @Override
24006    public ComponentName getInstantAppResolverSettingsComponent() {
24007        return mInstantAppResolverSettingsComponent;
24008    }
24009
24010    @Override
24011    public ComponentName getInstantAppInstallerComponent() {
24012        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24013            return null;
24014        }
24015        return mInstantAppInstallerActivity == null
24016                ? null : mInstantAppInstallerActivity.getComponentName();
24017    }
24018
24019    @Override
24020    public String getInstantAppAndroidId(String packageName, int userId) {
24021        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24022                "getInstantAppAndroidId");
24023        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24024                true /* requireFullPermission */, false /* checkShell */,
24025                "getInstantAppAndroidId");
24026        // Make sure the target is an Instant App.
24027        if (!isInstantApp(packageName, userId)) {
24028            return null;
24029        }
24030        synchronized (mPackages) {
24031            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24032        }
24033    }
24034
24035    boolean canHaveOatDir(String packageName) {
24036        synchronized (mPackages) {
24037            PackageParser.Package p = mPackages.get(packageName);
24038            if (p == null) {
24039                return false;
24040            }
24041            return p.canHaveOatDir();
24042        }
24043    }
24044
24045    private String getOatDir(PackageParser.Package pkg) {
24046        if (!pkg.canHaveOatDir()) {
24047            return null;
24048        }
24049        File codePath = new File(pkg.codePath);
24050        if (codePath.isDirectory()) {
24051            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24052        }
24053        return null;
24054    }
24055
24056    void deleteOatArtifactsOfPackage(String packageName) {
24057        final String[] instructionSets;
24058        final List<String> codePaths;
24059        final String oatDir;
24060        final PackageParser.Package pkg;
24061        synchronized (mPackages) {
24062            pkg = mPackages.get(packageName);
24063        }
24064        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24065        codePaths = pkg.getAllCodePaths();
24066        oatDir = getOatDir(pkg);
24067
24068        for (String codePath : codePaths) {
24069            for (String isa : instructionSets) {
24070                try {
24071                    mInstaller.deleteOdex(codePath, isa, oatDir);
24072                } catch (InstallerException e) {
24073                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24074                }
24075            }
24076        }
24077    }
24078
24079    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24080        Set<String> unusedPackages = new HashSet<>();
24081        long currentTimeInMillis = System.currentTimeMillis();
24082        synchronized (mPackages) {
24083            for (PackageParser.Package pkg : mPackages.values()) {
24084                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24085                if (ps == null) {
24086                    continue;
24087                }
24088                PackageDexUsage.PackageUseInfo packageUseInfo =
24089                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24090                if (PackageManagerServiceUtils
24091                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24092                                downgradeTimeThresholdMillis, packageUseInfo,
24093                                pkg.getLatestPackageUseTimeInMills(),
24094                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24095                    unusedPackages.add(pkg.packageName);
24096                }
24097            }
24098        }
24099        return unusedPackages;
24100    }
24101
24102    @Override
24103    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24104            int userId) {
24105        final int callingUid = Binder.getCallingUid();
24106        final int callingAppId = UserHandle.getAppId(callingUid);
24107
24108        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24109                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24110
24111        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24112                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24113            throw new SecurityException("Caller must have the "
24114                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24115        }
24116
24117        synchronized(mPackages) {
24118            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24119            scheduleWritePackageRestrictionsLocked(userId);
24120        }
24121    }
24122
24123    @Nullable
24124    @Override
24125    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24126        final int callingUid = Binder.getCallingUid();
24127        final int callingAppId = UserHandle.getAppId(callingUid);
24128
24129        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24130                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24131
24132        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24133                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24134            throw new SecurityException("Caller must have the "
24135                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24136        }
24137
24138        synchronized(mPackages) {
24139            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24140        }
24141    }
24142}
24143
24144interface PackageSender {
24145    /**
24146     * @param userIds User IDs where the action occurred on a full application
24147     * @param instantUserIds User IDs where the action occurred on an instant application
24148     */
24149    void sendPackageBroadcast(final String action, final String pkg,
24150        final Bundle extras, final int flags, final String targetPkg,
24151        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24152    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24153        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24154    void notifyPackageAdded(String packageName);
24155    void notifyPackageRemoved(String packageName);
24156}
24157