PackageManagerService.java revision 0da8537cf610cff71a2ef9ae946a7d3cb4232de4
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) {
2749                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2750                        }
2751                    }
2752                }
2753            }
2754
2755            //look for any incomplete package installations
2756            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2757            for (int i = 0; i < deletePkgsList.size(); i++) {
2758                // Actual deletion of code and data will be handled by later
2759                // reconciliation step
2760                final String packageName = deletePkgsList.get(i).name;
2761                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2762                synchronized (mPackages) {
2763                    mSettings.removePackageLPw(packageName);
2764                }
2765            }
2766
2767            //delete tmp files
2768            deleteTempPackageFiles();
2769
2770            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2771
2772            // Remove any shared userIDs that have no associated packages
2773            mSettings.pruneSharedUsersLPw();
2774            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2775            final int systemPackagesCount = mPackages.size();
2776            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2777                    + " ms, packageCount: " + systemPackagesCount
2778                    + " , timePerPackage: "
2779                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2780                    + " , cached: " + cachedSystemApps);
2781            if (mIsUpgrade && systemPackagesCount > 0) {
2782                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2783                        ((int) systemScanTime) / systemPackagesCount);
2784            }
2785            if (!mOnlyCore) {
2786                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2787                        SystemClock.uptimeMillis());
2788                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2789
2790                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2791                        | PackageParser.PARSE_FORWARD_LOCK,
2792                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2793
2794                // Remove disable package settings for updated system apps that were
2795                // removed via an OTA. If the update is no longer present, remove the
2796                // app completely. Otherwise, revoke their system privileges.
2797                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2798                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2799                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2800                    final String msg;
2801                    if (deletedPkg == null) {
2802                        // should have found an update, but, we didn't; remove everything
2803                        msg = "Updated system package " + deletedAppName
2804                                + " no longer exists; removing its data";
2805                        // Actual deletion of code and data will be handled by later
2806                        // reconciliation step
2807                    } else {
2808                        // found an update; revoke system privileges
2809                        msg = "Updated system package + " + deletedAppName
2810                                + " no longer exists; revoking system privileges";
2811
2812                        // Don't do anything if a stub is removed from the system image. If
2813                        // we were to remove the uncompressed version from the /data partition,
2814                        // this is where it'd be done.
2815
2816                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2817                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2818                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2819                    }
2820                    logCriticalInfo(Log.WARN, msg);
2821                }
2822
2823                /*
2824                 * Make sure all system apps that we expected to appear on
2825                 * the userdata partition actually showed up. If they never
2826                 * appeared, crawl back and revive the system version.
2827                 */
2828                for (int i = 0; i < mExpectingBetter.size(); i++) {
2829                    final String packageName = mExpectingBetter.keyAt(i);
2830                    if (!mPackages.containsKey(packageName)) {
2831                        final File scanFile = mExpectingBetter.valueAt(i);
2832
2833                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2834                                + " but never showed up; reverting to system");
2835
2836                        final @ParseFlags int reparseFlags;
2837                        final @ScanFlags int rescanFlags;
2838                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2839                            reparseFlags =
2840                                    mDefParseFlags |
2841                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2842                            rescanFlags =
2843                                    scanFlags
2844                                    | SCAN_AS_SYSTEM
2845                                    | SCAN_AS_PRIVILEGED;
2846                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2847                            reparseFlags =
2848                                    mDefParseFlags |
2849                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2850                            rescanFlags =
2851                                    scanFlags
2852                                    | SCAN_AS_SYSTEM;
2853                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2854                            reparseFlags =
2855                                    mDefParseFlags |
2856                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2857                            rescanFlags =
2858                                    scanFlags
2859                                    | SCAN_AS_SYSTEM
2860                                    | SCAN_AS_VENDOR
2861                                    | SCAN_AS_PRIVILEGED;
2862                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2863                            reparseFlags =
2864                                    mDefParseFlags |
2865                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2866                            rescanFlags =
2867                                    scanFlags
2868                                    | SCAN_AS_SYSTEM
2869                                    | SCAN_AS_VENDOR;
2870                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2871                            reparseFlags =
2872                                    mDefParseFlags |
2873                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2874                            rescanFlags =
2875                                    scanFlags
2876                                    | SCAN_AS_SYSTEM
2877                                    | SCAN_AS_OEM;
2878                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2879                            reparseFlags =
2880                                    mDefParseFlags |
2881                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2882                            rescanFlags =
2883                                    scanFlags
2884                                    | SCAN_AS_SYSTEM
2885                                    | SCAN_AS_PRODUCT
2886                                    | SCAN_AS_PRIVILEGED;
2887                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2888                            reparseFlags =
2889                                    mDefParseFlags |
2890                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2891                            rescanFlags =
2892                                    scanFlags
2893                                    | SCAN_AS_SYSTEM
2894                                    | SCAN_AS_PRODUCT;
2895                        } else {
2896                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2897                            continue;
2898                        }
2899
2900                        mSettings.enableSystemPackageLPw(packageName);
2901
2902                        try {
2903                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2904                        } catch (PackageManagerException e) {
2905                            Slog.e(TAG, "Failed to parse original system package: "
2906                                    + e.getMessage());
2907                        }
2908                    }
2909                }
2910
2911                // Uncompress and install any stubbed system applications.
2912                // This must be done last to ensure all stubs are replaced or disabled.
2913                decompressSystemApplications(stubSystemApps, scanFlags);
2914
2915                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2916                                - cachedSystemApps;
2917
2918                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2919                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2920                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2921                        + " ms, packageCount: " + dataPackagesCount
2922                        + " , timePerPackage: "
2923                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2924                        + " , cached: " + cachedNonSystemApps);
2925                if (mIsUpgrade && dataPackagesCount > 0) {
2926                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2927                            ((int) dataScanTime) / dataPackagesCount);
2928                }
2929            }
2930            mExpectingBetter.clear();
2931
2932            // Resolve the storage manager.
2933            mStorageManagerPackage = getStorageManagerPackageName();
2934
2935            // Resolve protected action filters. Only the setup wizard is allowed to
2936            // have a high priority filter for these actions.
2937            mSetupWizardPackage = getSetupWizardPackageName();
2938            if (mProtectedFilters.size() > 0) {
2939                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2940                    Slog.i(TAG, "No setup wizard;"
2941                        + " All protected intents capped to priority 0");
2942                }
2943                for (ActivityIntentInfo filter : mProtectedFilters) {
2944                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2945                        if (DEBUG_FILTERS) {
2946                            Slog.i(TAG, "Found setup wizard;"
2947                                + " allow priority " + filter.getPriority() + ";"
2948                                + " package: " + filter.activity.info.packageName
2949                                + " activity: " + filter.activity.className
2950                                + " priority: " + filter.getPriority());
2951                        }
2952                        // skip setup wizard; allow it to keep the high priority filter
2953                        continue;
2954                    }
2955                    if (DEBUG_FILTERS) {
2956                        Slog.i(TAG, "Protected action; cap priority to 0;"
2957                                + " package: " + filter.activity.info.packageName
2958                                + " activity: " + filter.activity.className
2959                                + " origPrio: " + filter.getPriority());
2960                    }
2961                    filter.setPriority(0);
2962                }
2963            }
2964            mDeferProtectedFilters = false;
2965            mProtectedFilters.clear();
2966
2967            // Now that we know all of the shared libraries, update all clients to have
2968            // the correct library paths.
2969            updateAllSharedLibrariesLPw(null);
2970
2971            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2972                // NOTE: We ignore potential failures here during a system scan (like
2973                // the rest of the commands above) because there's precious little we
2974                // can do about it. A settings error is reported, though.
2975                final List<String> changedAbiCodePath =
2976                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2977                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2978                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
2979                        final String codePathString = changedAbiCodePath.get(i);
2980                        try {
2981                            mInstaller.rmdex(codePathString,
2982                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2983                        } catch (InstallerException ignored) {
2984                        }
2985                    }
2986                }
2987            }
2988
2989            // Now that we know all the packages we are keeping,
2990            // read and update their last usage times.
2991            mPackageUsage.read(mPackages);
2992            mCompilerStats.read();
2993
2994            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2995                    SystemClock.uptimeMillis());
2996            Slog.i(TAG, "Time to scan packages: "
2997                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2998                    + " seconds");
2999
3000            // If the platform SDK has changed since the last time we booted,
3001            // we need to re-grant app permission to catch any new ones that
3002            // appear.  This is really a hack, and means that apps can in some
3003            // cases get permissions that the user didn't initially explicitly
3004            // allow...  it would be nice to have some better way to handle
3005            // this situation.
3006            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3007            if (sdkUpdated) {
3008                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3009                        + mSdkVersion + "; regranting permissions for internal storage");
3010            }
3011            mPermissionManager.updateAllPermissions(
3012                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3013                    mPermissionCallback);
3014            ver.sdkVersion = mSdkVersion;
3015
3016            // If this is the first boot or an update from pre-M, and it is a normal
3017            // boot, then we need to initialize the default preferred apps across
3018            // all defined users.
3019            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3020                for (UserInfo user : sUserManager.getUsers(true)) {
3021                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3022                    applyFactoryDefaultBrowserLPw(user.id);
3023                    primeDomainVerificationsLPw(user.id);
3024                }
3025            }
3026
3027            // Prepare storage for system user really early during boot,
3028            // since core system apps like SettingsProvider and SystemUI
3029            // can't wait for user to start
3030            final int storageFlags;
3031            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3032                storageFlags = StorageManager.FLAG_STORAGE_DE;
3033            } else {
3034                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3035            }
3036            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3037                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3038                    true /* onlyCoreApps */);
3039            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3040                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3041                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3042                traceLog.traceBegin("AppDataFixup");
3043                try {
3044                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3045                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3046                } catch (InstallerException e) {
3047                    Slog.w(TAG, "Trouble fixing GIDs", e);
3048                }
3049                traceLog.traceEnd();
3050
3051                traceLog.traceBegin("AppDataPrepare");
3052                if (deferPackages == null || deferPackages.isEmpty()) {
3053                    return;
3054                }
3055                int count = 0;
3056                for (String pkgName : deferPackages) {
3057                    PackageParser.Package pkg = null;
3058                    synchronized (mPackages) {
3059                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3060                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3061                            pkg = ps.pkg;
3062                        }
3063                    }
3064                    if (pkg != null) {
3065                        synchronized (mInstallLock) {
3066                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3067                                    true /* maybeMigrateAppData */);
3068                        }
3069                        count++;
3070                    }
3071                }
3072                traceLog.traceEnd();
3073                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3074            }, "prepareAppData");
3075
3076            // If this is first boot after an OTA, and a normal boot, then
3077            // we need to clear code cache directories.
3078            // Note that we do *not* clear the application profiles. These remain valid
3079            // across OTAs and are used to drive profile verification (post OTA) and
3080            // profile compilation (without waiting to collect a fresh set of profiles).
3081            if (mIsUpgrade && !onlyCore) {
3082                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3083                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3084                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3085                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3086                        // No apps are running this early, so no need to freeze
3087                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3088                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3089                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3090                    }
3091                }
3092                ver.fingerprint = Build.FINGERPRINT;
3093            }
3094
3095            checkDefaultBrowser();
3096
3097            // clear only after permissions and other defaults have been updated
3098            mExistingSystemPackages.clear();
3099            mPromoteSystemApps = false;
3100
3101            // All the changes are done during package scanning.
3102            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3103
3104            // can downgrade to reader
3105            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3106            mSettings.writeLPr();
3107            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3108            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3109                    SystemClock.uptimeMillis());
3110
3111            if (!mOnlyCore) {
3112                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3113                mRequiredInstallerPackage = getRequiredInstallerLPr();
3114                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3115                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3116                if (mIntentFilterVerifierComponent != null) {
3117                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3118                            mIntentFilterVerifierComponent);
3119                } else {
3120                    mIntentFilterVerifier = null;
3121                }
3122                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3123                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3124                        SharedLibraryInfo.VERSION_UNDEFINED);
3125                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3126                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3127                        SharedLibraryInfo.VERSION_UNDEFINED);
3128            } else {
3129                mRequiredVerifierPackage = null;
3130                mRequiredInstallerPackage = null;
3131                mRequiredUninstallerPackage = null;
3132                mIntentFilterVerifierComponent = null;
3133                mIntentFilterVerifier = null;
3134                mServicesSystemSharedLibraryPackageName = null;
3135                mSharedSystemSharedLibraryPackageName = null;
3136            }
3137
3138            mInstallerService = new PackageInstallerService(context, this);
3139            final Pair<ComponentName, String> instantAppResolverComponent =
3140                    getInstantAppResolverLPr();
3141            if (instantAppResolverComponent != null) {
3142                if (DEBUG_INSTANT) {
3143                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3144                }
3145                mInstantAppResolverConnection = new InstantAppResolverConnection(
3146                        mContext, instantAppResolverComponent.first,
3147                        instantAppResolverComponent.second);
3148                mInstantAppResolverSettingsComponent =
3149                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3150            } else {
3151                mInstantAppResolverConnection = null;
3152                mInstantAppResolverSettingsComponent = null;
3153            }
3154            updateInstantAppInstallerLocked(null);
3155
3156            // Read and update the usage of dex files.
3157            // Do this at the end of PM init so that all the packages have their
3158            // data directory reconciled.
3159            // At this point we know the code paths of the packages, so we can validate
3160            // the disk file and build the internal cache.
3161            // The usage file is expected to be small so loading and verifying it
3162            // should take a fairly small time compare to the other activities (e.g. package
3163            // scanning).
3164            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3165            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3166            for (int userId : currentUserIds) {
3167                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3168            }
3169            mDexManager.load(userPackages);
3170            if (mIsUpgrade) {
3171                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3172                        (int) (SystemClock.uptimeMillis() - startTime));
3173            }
3174        } // synchronized (mPackages)
3175        } // synchronized (mInstallLock)
3176
3177        // Now after opening every single application zip, make sure they
3178        // are all flushed.  Not really needed, but keeps things nice and
3179        // tidy.
3180        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3181        Runtime.getRuntime().gc();
3182        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3183
3184        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3185        FallbackCategoryProvider.loadFallbacks();
3186        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3187
3188        // The initial scanning above does many calls into installd while
3189        // holding the mPackages lock, but we're mostly interested in yelling
3190        // once we have a booted system.
3191        mInstaller.setWarnIfHeld(mPackages);
3192
3193        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3194    }
3195
3196    /**
3197     * Uncompress and install stub applications.
3198     * <p>In order to save space on the system partition, some applications are shipped in a
3199     * compressed form. In addition the compressed bits for the full application, the
3200     * system image contains a tiny stub comprised of only the Android manifest.
3201     * <p>During the first boot, attempt to uncompress and install the full application. If
3202     * the application can't be installed for any reason, disable the stub and prevent
3203     * uncompressing the full application during future boots.
3204     * <p>In order to forcefully attempt an installation of a full application, go to app
3205     * settings and enable the application.
3206     */
3207    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3208        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3209            final String pkgName = stubSystemApps.get(i);
3210            // skip if the system package is already disabled
3211            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3212                stubSystemApps.remove(i);
3213                continue;
3214            }
3215            // skip if the package isn't installed (?!); this should never happen
3216            final PackageParser.Package pkg = mPackages.get(pkgName);
3217            if (pkg == null) {
3218                stubSystemApps.remove(i);
3219                continue;
3220            }
3221            // skip if the package has been disabled by the user
3222            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3223            if (ps != null) {
3224                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3225                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3226                    stubSystemApps.remove(i);
3227                    continue;
3228                }
3229            }
3230
3231            if (DEBUG_COMPRESSION) {
3232                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3233            }
3234
3235            // uncompress the binary to its eventual destination on /data
3236            final File scanFile = decompressPackage(pkg);
3237            if (scanFile == null) {
3238                continue;
3239            }
3240
3241            // install the package to replace the stub on /system
3242            try {
3243                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3244                removePackageLI(pkg, true /*chatty*/);
3245                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3246                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3247                        UserHandle.USER_SYSTEM, "android");
3248                stubSystemApps.remove(i);
3249                continue;
3250            } catch (PackageManagerException e) {
3251                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3252            }
3253
3254            // any failed attempt to install the package will be cleaned up later
3255        }
3256
3257        // disable any stub still left; these failed to install the full application
3258        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3259            final String pkgName = stubSystemApps.get(i);
3260            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3261            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3262                    UserHandle.USER_SYSTEM, "android");
3263            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3264        }
3265    }
3266
3267    /**
3268     * Decompresses the given package on the system image onto
3269     * the /data partition.
3270     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3271     */
3272    private File decompressPackage(PackageParser.Package pkg) {
3273        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3274        if (compressedFiles == null || compressedFiles.length == 0) {
3275            if (DEBUG_COMPRESSION) {
3276                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3277            }
3278            return null;
3279        }
3280        final File dstCodePath =
3281                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3282        int ret = PackageManager.INSTALL_SUCCEEDED;
3283        try {
3284            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3285            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3286            for (File srcFile : compressedFiles) {
3287                final String srcFileName = srcFile.getName();
3288                final String dstFileName = srcFileName.substring(
3289                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3290                final File dstFile = new File(dstCodePath, dstFileName);
3291                ret = decompressFile(srcFile, dstFile);
3292                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3293                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3294                            + "; pkg: " + pkg.packageName
3295                            + ", file: " + dstFileName);
3296                    break;
3297                }
3298            }
3299        } catch (ErrnoException e) {
3300            logCriticalInfo(Log.ERROR, "Failed to decompress"
3301                    + "; pkg: " + pkg.packageName
3302                    + ", err: " + e.errno);
3303        }
3304        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3305            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3306            NativeLibraryHelper.Handle handle = null;
3307            try {
3308                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3309                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3310                        null /*abiOverride*/);
3311            } catch (IOException e) {
3312                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3313                        + "; pkg: " + pkg.packageName);
3314                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3315            } finally {
3316                IoUtils.closeQuietly(handle);
3317            }
3318        }
3319        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3320            if (dstCodePath == null || !dstCodePath.exists()) {
3321                return null;
3322            }
3323            removeCodePathLI(dstCodePath);
3324            return null;
3325        }
3326
3327        return dstCodePath;
3328    }
3329
3330    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3331        // we're only interested in updating the installer appliction when 1) it's not
3332        // already set or 2) the modified package is the installer
3333        if (mInstantAppInstallerActivity != null
3334                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3335                        .equals(modifiedPackage)) {
3336            return;
3337        }
3338        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3339    }
3340
3341    private static File preparePackageParserCache(boolean isUpgrade) {
3342        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3343            return null;
3344        }
3345
3346        // Disable package parsing on eng builds to allow for faster incremental development.
3347        if (Build.IS_ENG) {
3348            return null;
3349        }
3350
3351        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3352            Slog.i(TAG, "Disabling package parser cache due to system property.");
3353            return null;
3354        }
3355
3356        // The base directory for the package parser cache lives under /data/system/.
3357        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3358                "package_cache");
3359        if (cacheBaseDir == null) {
3360            return null;
3361        }
3362
3363        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3364        // This also serves to "GC" unused entries when the package cache version changes (which
3365        // can only happen during upgrades).
3366        if (isUpgrade) {
3367            FileUtils.deleteContents(cacheBaseDir);
3368        }
3369
3370
3371        // Return the versioned package cache directory. This is something like
3372        // "/data/system/package_cache/1"
3373        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3374
3375        // The following is a workaround to aid development on non-numbered userdebug
3376        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3377        // the system partition is newer.
3378        //
3379        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3380        // that starts with "eng." to signify that this is an engineering build and not
3381        // destined for release.
3382        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3383            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3384
3385            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3386            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3387            // in general and should not be used for production changes. In this specific case,
3388            // we know that they will work.
3389            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3390            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3391                FileUtils.deleteContents(cacheBaseDir);
3392                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3393            }
3394        }
3395
3396        return cacheDir;
3397    }
3398
3399    @Override
3400    public boolean isFirstBoot() {
3401        // allow instant applications
3402        return mFirstBoot;
3403    }
3404
3405    @Override
3406    public boolean isOnlyCoreApps() {
3407        // allow instant applications
3408        return mOnlyCore;
3409    }
3410
3411    @Override
3412    public boolean isUpgrade() {
3413        // allow instant applications
3414        // The system property allows testing ota flow when upgraded to the same image.
3415        return mIsUpgrade || SystemProperties.getBoolean(
3416                "persist.pm.mock-upgrade", false /* default */);
3417    }
3418
3419    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3420        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3421
3422        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3423                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3424                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3425        if (matches.size() == 1) {
3426            return matches.get(0).getComponentInfo().packageName;
3427        } else if (matches.size() == 0) {
3428            Log.e(TAG, "There should probably be a verifier, but, none were found");
3429            return null;
3430        }
3431        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3432    }
3433
3434    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3435        synchronized (mPackages) {
3436            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3437            if (libraryEntry == null) {
3438                throw new IllegalStateException("Missing required shared library:" + name);
3439            }
3440            return libraryEntry.apk;
3441        }
3442    }
3443
3444    private @NonNull String getRequiredInstallerLPr() {
3445        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3446        intent.addCategory(Intent.CATEGORY_DEFAULT);
3447        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3448
3449        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3450                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3451                UserHandle.USER_SYSTEM);
3452        if (matches.size() == 1) {
3453            ResolveInfo resolveInfo = matches.get(0);
3454            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3455                throw new RuntimeException("The installer must be a privileged app");
3456            }
3457            return matches.get(0).getComponentInfo().packageName;
3458        } else {
3459            throw new RuntimeException("There must be exactly one installer; found " + matches);
3460        }
3461    }
3462
3463    private @NonNull String getRequiredUninstallerLPr() {
3464        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3465        intent.addCategory(Intent.CATEGORY_DEFAULT);
3466        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3467
3468        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3469                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3470                UserHandle.USER_SYSTEM);
3471        if (resolveInfo == null ||
3472                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3473            throw new RuntimeException("There must be exactly one uninstaller; found "
3474                    + resolveInfo);
3475        }
3476        return resolveInfo.getComponentInfo().packageName;
3477    }
3478
3479    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3480        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3481
3482        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3483                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3484                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3485        ResolveInfo best = null;
3486        final int N = matches.size();
3487        for (int i = 0; i < N; i++) {
3488            final ResolveInfo cur = matches.get(i);
3489            final String packageName = cur.getComponentInfo().packageName;
3490            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3491                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3492                continue;
3493            }
3494
3495            if (best == null || cur.priority > best.priority) {
3496                best = cur;
3497            }
3498        }
3499
3500        if (best != null) {
3501            return best.getComponentInfo().getComponentName();
3502        }
3503        Slog.w(TAG, "Intent filter verifier not found");
3504        return null;
3505    }
3506
3507    @Override
3508    public @Nullable ComponentName getInstantAppResolverComponent() {
3509        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3510            return null;
3511        }
3512        synchronized (mPackages) {
3513            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3514            if (instantAppResolver == null) {
3515                return null;
3516            }
3517            return instantAppResolver.first;
3518        }
3519    }
3520
3521    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3522        final String[] packageArray =
3523                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3524        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3525            if (DEBUG_INSTANT) {
3526                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3527            }
3528            return null;
3529        }
3530
3531        final int callingUid = Binder.getCallingUid();
3532        final int resolveFlags =
3533                MATCH_DIRECT_BOOT_AWARE
3534                | MATCH_DIRECT_BOOT_UNAWARE
3535                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3536        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3537        final Intent resolverIntent = new Intent(actionName);
3538        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3539                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3540        final int N = resolvers.size();
3541        if (N == 0) {
3542            if (DEBUG_INSTANT) {
3543                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3544            }
3545            return null;
3546        }
3547
3548        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3549        for (int i = 0; i < N; i++) {
3550            final ResolveInfo info = resolvers.get(i);
3551
3552            if (info.serviceInfo == null) {
3553                continue;
3554            }
3555
3556            final String packageName = info.serviceInfo.packageName;
3557            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3558                if (DEBUG_INSTANT) {
3559                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3560                            + " pkg: " + packageName + ", info:" + info);
3561                }
3562                continue;
3563            }
3564
3565            if (DEBUG_INSTANT) {
3566                Slog.v(TAG, "Ephemeral resolver found;"
3567                        + " pkg: " + packageName + ", info:" + info);
3568            }
3569            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3570        }
3571        if (DEBUG_INSTANT) {
3572            Slog.v(TAG, "Ephemeral resolver NOT found");
3573        }
3574        return null;
3575    }
3576
3577    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3578        String[] orderedActions = Build.IS_ENG
3579                ? new String[]{
3580                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3581                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3582                : new String[]{
3583                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3584
3585        final int resolveFlags =
3586                MATCH_DIRECT_BOOT_AWARE
3587                        | MATCH_DIRECT_BOOT_UNAWARE
3588                        | Intent.FLAG_IGNORE_EPHEMERAL
3589                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3590        final Intent intent = new Intent();
3591        intent.addCategory(Intent.CATEGORY_DEFAULT);
3592        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3593        List<ResolveInfo> matches = null;
3594        for (String action : orderedActions) {
3595            intent.setAction(action);
3596            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3597                    resolveFlags, UserHandle.USER_SYSTEM);
3598            if (matches.isEmpty()) {
3599                if (DEBUG_INSTANT) {
3600                    Slog.d(TAG, "Instant App installer not found with " + action);
3601                }
3602            } else {
3603                break;
3604            }
3605        }
3606        Iterator<ResolveInfo> iter = matches.iterator();
3607        while (iter.hasNext()) {
3608            final ResolveInfo rInfo = iter.next();
3609            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3610            if (ps != null) {
3611                final PermissionsState permissionsState = ps.getPermissionsState();
3612                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3613                        || Build.IS_ENG) {
3614                    continue;
3615                }
3616            }
3617            iter.remove();
3618        }
3619        if (matches.size() == 0) {
3620            return null;
3621        } else if (matches.size() == 1) {
3622            return (ActivityInfo) matches.get(0).getComponentInfo();
3623        } else {
3624            throw new RuntimeException(
3625                    "There must be at most one ephemeral installer; found " + matches);
3626        }
3627    }
3628
3629    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3630            @NonNull ComponentName resolver) {
3631        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3632                .addCategory(Intent.CATEGORY_DEFAULT)
3633                .setPackage(resolver.getPackageName());
3634        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3635        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3636                UserHandle.USER_SYSTEM);
3637        if (matches.isEmpty()) {
3638            return null;
3639        }
3640        return matches.get(0).getComponentInfo().getComponentName();
3641    }
3642
3643    private void primeDomainVerificationsLPw(int userId) {
3644        if (DEBUG_DOMAIN_VERIFICATION) {
3645            Slog.d(TAG, "Priming domain verifications in user " + userId);
3646        }
3647
3648        SystemConfig systemConfig = SystemConfig.getInstance();
3649        ArraySet<String> packages = systemConfig.getLinkedApps();
3650
3651        for (String packageName : packages) {
3652            PackageParser.Package pkg = mPackages.get(packageName);
3653            if (pkg != null) {
3654                if (!pkg.isSystem()) {
3655                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3656                    continue;
3657                }
3658
3659                ArraySet<String> domains = null;
3660                for (PackageParser.Activity a : pkg.activities) {
3661                    for (ActivityIntentInfo filter : a.intents) {
3662                        if (hasValidDomains(filter)) {
3663                            if (domains == null) {
3664                                domains = new ArraySet<String>();
3665                            }
3666                            domains.addAll(filter.getHostsList());
3667                        }
3668                    }
3669                }
3670
3671                if (domains != null && domains.size() > 0) {
3672                    if (DEBUG_DOMAIN_VERIFICATION) {
3673                        Slog.v(TAG, "      + " + packageName);
3674                    }
3675                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3676                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3677                    // and then 'always' in the per-user state actually used for intent resolution.
3678                    final IntentFilterVerificationInfo ivi;
3679                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3680                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3681                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3682                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3683                } else {
3684                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3685                            + "' does not handle web links");
3686                }
3687            } else {
3688                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3689            }
3690        }
3691
3692        scheduleWritePackageRestrictionsLocked(userId);
3693        scheduleWriteSettingsLocked();
3694    }
3695
3696    private void applyFactoryDefaultBrowserLPw(int userId) {
3697        // The default browser app's package name is stored in a string resource,
3698        // with a product-specific overlay used for vendor customization.
3699        String browserPkg = mContext.getResources().getString(
3700                com.android.internal.R.string.default_browser);
3701        if (!TextUtils.isEmpty(browserPkg)) {
3702            // non-empty string => required to be a known package
3703            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3704            if (ps == null) {
3705                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3706                browserPkg = null;
3707            } else {
3708                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3709            }
3710        }
3711
3712        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3713        // default.  If there's more than one, just leave everything alone.
3714        if (browserPkg == null) {
3715            calculateDefaultBrowserLPw(userId);
3716        }
3717    }
3718
3719    private void calculateDefaultBrowserLPw(int userId) {
3720        List<String> allBrowsers = resolveAllBrowserApps(userId);
3721        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3722        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3723    }
3724
3725    private List<String> resolveAllBrowserApps(int userId) {
3726        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3727        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3728                PackageManager.MATCH_ALL, userId);
3729
3730        final int count = list.size();
3731        List<String> result = new ArrayList<String>(count);
3732        for (int i=0; i<count; i++) {
3733            ResolveInfo info = list.get(i);
3734            if (info.activityInfo == null
3735                    || !info.handleAllWebDataURI
3736                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3737                    || result.contains(info.activityInfo.packageName)) {
3738                continue;
3739            }
3740            result.add(info.activityInfo.packageName);
3741        }
3742
3743        return result;
3744    }
3745
3746    private boolean packageIsBrowser(String packageName, int userId) {
3747        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3748                PackageManager.MATCH_ALL, userId);
3749        final int N = list.size();
3750        for (int i = 0; i < N; i++) {
3751            ResolveInfo info = list.get(i);
3752            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3753                return true;
3754            }
3755        }
3756        return false;
3757    }
3758
3759    private void checkDefaultBrowser() {
3760        final int myUserId = UserHandle.myUserId();
3761        final String packageName = getDefaultBrowserPackageName(myUserId);
3762        if (packageName != null) {
3763            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3764            if (info == null) {
3765                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3766                synchronized (mPackages) {
3767                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3768                }
3769            }
3770        }
3771    }
3772
3773    @Override
3774    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3775            throws RemoteException {
3776        try {
3777            return super.onTransact(code, data, reply, flags);
3778        } catch (RuntimeException e) {
3779            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3780                Slog.wtf(TAG, "Package Manager Crash", e);
3781            }
3782            throw e;
3783        }
3784    }
3785
3786    static int[] appendInts(int[] cur, int[] add) {
3787        if (add == null) return cur;
3788        if (cur == null) return add;
3789        final int N = add.length;
3790        for (int i=0; i<N; i++) {
3791            cur = appendInt(cur, add[i]);
3792        }
3793        return cur;
3794    }
3795
3796    /**
3797     * Returns whether or not a full application can see an instant application.
3798     * <p>
3799     * Currently, there are three cases in which this can occur:
3800     * <ol>
3801     * <li>The calling application is a "special" process. Special processes
3802     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3803     * <li>The calling application has the permission
3804     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3805     * <li>The calling application is the default launcher on the
3806     *     system partition.</li>
3807     * </ol>
3808     */
3809    private boolean canViewInstantApps(int callingUid, int userId) {
3810        if (callingUid < Process.FIRST_APPLICATION_UID) {
3811            return true;
3812        }
3813        if (mContext.checkCallingOrSelfPermission(
3814                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3815            return true;
3816        }
3817        if (mContext.checkCallingOrSelfPermission(
3818                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3819            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3820            if (homeComponent != null
3821                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3822                return true;
3823            }
3824        }
3825        return false;
3826    }
3827
3828    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3829        if (!sUserManager.exists(userId)) return null;
3830        if (ps == null) {
3831            return null;
3832        }
3833        final int callingUid = Binder.getCallingUid();
3834        // Filter out ephemeral app metadata:
3835        //   * The system/shell/root can see metadata for any app
3836        //   * An installed app can see metadata for 1) other installed apps
3837        //     and 2) ephemeral apps that have explicitly interacted with it
3838        //   * Ephemeral apps can only see their own data and exposed installed apps
3839        //   * Holding a signature permission allows seeing instant apps
3840        if (filterAppAccessLPr(ps, callingUid, userId)) {
3841            return null;
3842        }
3843
3844        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3845                && ps.isSystem()) {
3846            flags |= MATCH_ANY_USER;
3847        }
3848
3849        final PackageUserState state = ps.readUserState(userId);
3850        PackageParser.Package p = ps.pkg;
3851        if (p != null) {
3852            final PermissionsState permissionsState = ps.getPermissionsState();
3853
3854            // Compute GIDs only if requested
3855            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3856                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3857            // Compute granted permissions only if package has requested permissions
3858            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3859                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3860
3861            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3862                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3863
3864            if (packageInfo == null) {
3865                return null;
3866            }
3867
3868            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3869                    resolveExternalPackageNameLPr(p);
3870
3871            return packageInfo;
3872        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3873            PackageInfo pi = new PackageInfo();
3874            pi.packageName = ps.name;
3875            pi.setLongVersionCode(ps.versionCode);
3876            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3877            pi.firstInstallTime = ps.firstInstallTime;
3878            pi.lastUpdateTime = ps.lastUpdateTime;
3879
3880            ApplicationInfo ai = new ApplicationInfo();
3881            ai.packageName = ps.name;
3882            ai.uid = UserHandle.getUid(userId, ps.appId);
3883            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3884            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3885            ai.versionCode = ps.versionCode;
3886            ai.flags = ps.pkgFlags;
3887            ai.privateFlags = ps.pkgPrivateFlags;
3888            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3889
3890            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3891                    + ps.name + "]. Provides a minimum info.");
3892            return pi;
3893        } else {
3894            return null;
3895        }
3896    }
3897
3898    @Override
3899    public void checkPackageStartable(String packageName, int userId) {
3900        final int callingUid = Binder.getCallingUid();
3901        if (getInstantAppPackageName(callingUid) != null) {
3902            throw new SecurityException("Instant applications don't have access to this method");
3903        }
3904        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3905        synchronized (mPackages) {
3906            final PackageSetting ps = mSettings.mPackages.get(packageName);
3907            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3908                throw new SecurityException("Package " + packageName + " was not found!");
3909            }
3910
3911            if (!ps.getInstalled(userId)) {
3912                throw new SecurityException(
3913                        "Package " + packageName + " was not installed for user " + userId + "!");
3914            }
3915
3916            if (mSafeMode && !ps.isSystem()) {
3917                throw new SecurityException("Package " + packageName + " not a system app!");
3918            }
3919
3920            if (mFrozenPackages.contains(packageName)) {
3921                throw new SecurityException("Package " + packageName + " is currently frozen!");
3922            }
3923
3924            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3925                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3926            }
3927        }
3928    }
3929
3930    @Override
3931    public boolean isPackageAvailable(String packageName, int userId) {
3932        if (!sUserManager.exists(userId)) return false;
3933        final int callingUid = Binder.getCallingUid();
3934        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3935                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3936        synchronized (mPackages) {
3937            PackageParser.Package p = mPackages.get(packageName);
3938            if (p != null) {
3939                final PackageSetting ps = (PackageSetting) p.mExtras;
3940                if (filterAppAccessLPr(ps, callingUid, userId)) {
3941                    return false;
3942                }
3943                if (ps != null) {
3944                    final PackageUserState state = ps.readUserState(userId);
3945                    if (state != null) {
3946                        return PackageParser.isAvailable(state);
3947                    }
3948                }
3949            }
3950        }
3951        return false;
3952    }
3953
3954    @Override
3955    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3956        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3957                flags, Binder.getCallingUid(), userId);
3958    }
3959
3960    @Override
3961    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3962            int flags, int userId) {
3963        return getPackageInfoInternal(versionedPackage.getPackageName(),
3964                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3965    }
3966
3967    /**
3968     * Important: The provided filterCallingUid is used exclusively to filter out packages
3969     * that can be seen based on user state. It's typically the original caller uid prior
3970     * to clearing. Because it can only be provided by trusted code, it's value can be
3971     * trusted and will be used as-is; unlike userId which will be validated by this method.
3972     */
3973    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3974            int flags, int filterCallingUid, int userId) {
3975        if (!sUserManager.exists(userId)) return null;
3976        flags = updateFlagsForPackage(flags, userId, packageName);
3977        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3978                false /* requireFullPermission */, false /* checkShell */, "get package info");
3979
3980        // reader
3981        synchronized (mPackages) {
3982            // Normalize package name to handle renamed packages and static libs
3983            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3984
3985            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3986            if (matchFactoryOnly) {
3987                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3988                if (ps != null) {
3989                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3990                        return null;
3991                    }
3992                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3993                        return null;
3994                    }
3995                    return generatePackageInfo(ps, flags, userId);
3996                }
3997            }
3998
3999            PackageParser.Package p = mPackages.get(packageName);
4000            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4001                return null;
4002            }
4003            if (DEBUG_PACKAGE_INFO)
4004                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4005            if (p != null) {
4006                final PackageSetting ps = (PackageSetting) p.mExtras;
4007                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4008                    return null;
4009                }
4010                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4011                    return null;
4012                }
4013                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4014            }
4015            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4016                final PackageSetting ps = mSettings.mPackages.get(packageName);
4017                if (ps == null) return null;
4018                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4019                    return null;
4020                }
4021                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4022                    return null;
4023                }
4024                return generatePackageInfo(ps, flags, userId);
4025            }
4026        }
4027        return null;
4028    }
4029
4030    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4031        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4032            return true;
4033        }
4034        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4035            return true;
4036        }
4037        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4038            return true;
4039        }
4040        return false;
4041    }
4042
4043    private boolean isComponentVisibleToInstantApp(
4044            @Nullable ComponentName component, @ComponentType int type) {
4045        if (type == TYPE_ACTIVITY) {
4046            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4047            return activity != null
4048                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4049                    : false;
4050        } else if (type == TYPE_RECEIVER) {
4051            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4052            return activity != null
4053                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4054                    : false;
4055        } else if (type == TYPE_SERVICE) {
4056            final PackageParser.Service service = mServices.mServices.get(component);
4057            return service != null
4058                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4059                    : false;
4060        } else if (type == TYPE_PROVIDER) {
4061            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4062            return provider != null
4063                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4064                    : false;
4065        } else if (type == TYPE_UNKNOWN) {
4066            return isComponentVisibleToInstantApp(component);
4067        }
4068        return false;
4069    }
4070
4071    /**
4072     * Returns whether or not access to the application should be filtered.
4073     * <p>
4074     * Access may be limited based upon whether the calling or target applications
4075     * are instant applications.
4076     *
4077     * @see #canAccessInstantApps(int)
4078     */
4079    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4080            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4081        // if we're in an isolated process, get the real calling UID
4082        if (Process.isIsolated(callingUid)) {
4083            callingUid = mIsolatedOwners.get(callingUid);
4084        }
4085        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4086        final boolean callerIsInstantApp = instantAppPkgName != null;
4087        if (ps == null) {
4088            if (callerIsInstantApp) {
4089                // pretend the application exists, but, needs to be filtered
4090                return true;
4091            }
4092            return false;
4093        }
4094        // if the target and caller are the same application, don't filter
4095        if (isCallerSameApp(ps.name, callingUid)) {
4096            return false;
4097        }
4098        if (callerIsInstantApp) {
4099            // request for a specific component; if it hasn't been explicitly exposed, filter
4100            if (component != null) {
4101                return !isComponentVisibleToInstantApp(component, componentType);
4102            }
4103            // request for application; if no components have been explicitly exposed, filter
4104            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4105        }
4106        if (ps.getInstantApp(userId)) {
4107            // caller can see all components of all instant applications, don't filter
4108            if (canViewInstantApps(callingUid, userId)) {
4109                return false;
4110            }
4111            // request for a specific instant application component, filter
4112            if (component != null) {
4113                return true;
4114            }
4115            // request for an instant application; if the caller hasn't been granted access, filter
4116            return !mInstantAppRegistry.isInstantAccessGranted(
4117                    userId, UserHandle.getAppId(callingUid), ps.appId);
4118        }
4119        return false;
4120    }
4121
4122    /**
4123     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4124     */
4125    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4126        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4127    }
4128
4129    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4130            int flags) {
4131        // Callers can access only the libs they depend on, otherwise they need to explicitly
4132        // ask for the shared libraries given the caller is allowed to access all static libs.
4133        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4134            // System/shell/root get to see all static libs
4135            final int appId = UserHandle.getAppId(uid);
4136            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4137                    || appId == Process.ROOT_UID) {
4138                return false;
4139            }
4140        }
4141
4142        // No package means no static lib as it is always on internal storage
4143        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4144            return false;
4145        }
4146
4147        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4148                ps.pkg.staticSharedLibVersion);
4149        if (libEntry == null) {
4150            return false;
4151        }
4152
4153        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4154        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4155        if (uidPackageNames == null) {
4156            return true;
4157        }
4158
4159        for (String uidPackageName : uidPackageNames) {
4160            if (ps.name.equals(uidPackageName)) {
4161                return false;
4162            }
4163            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4164            if (uidPs != null) {
4165                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4166                        libEntry.info.getName());
4167                if (index < 0) {
4168                    continue;
4169                }
4170                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4171                    return false;
4172                }
4173            }
4174        }
4175        return true;
4176    }
4177
4178    @Override
4179    public String[] currentToCanonicalPackageNames(String[] names) {
4180        final int callingUid = Binder.getCallingUid();
4181        if (getInstantAppPackageName(callingUid) != null) {
4182            return names;
4183        }
4184        final String[] out = new String[names.length];
4185        // reader
4186        synchronized (mPackages) {
4187            final int callingUserId = UserHandle.getUserId(callingUid);
4188            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4189            for (int i=names.length-1; i>=0; i--) {
4190                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4191                boolean translateName = false;
4192                if (ps != null && ps.realName != null) {
4193                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4194                    translateName = !targetIsInstantApp
4195                            || canViewInstantApps
4196                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4197                                    UserHandle.getAppId(callingUid), ps.appId);
4198                }
4199                out[i] = translateName ? ps.realName : names[i];
4200            }
4201        }
4202        return out;
4203    }
4204
4205    @Override
4206    public String[] canonicalToCurrentPackageNames(String[] names) {
4207        final int callingUid = Binder.getCallingUid();
4208        if (getInstantAppPackageName(callingUid) != null) {
4209            return names;
4210        }
4211        final String[] out = new String[names.length];
4212        // reader
4213        synchronized (mPackages) {
4214            final int callingUserId = UserHandle.getUserId(callingUid);
4215            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4216            for (int i=names.length-1; i>=0; i--) {
4217                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4218                boolean translateName = false;
4219                if (cur != null) {
4220                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4221                    final boolean targetIsInstantApp =
4222                            ps != null && ps.getInstantApp(callingUserId);
4223                    translateName = !targetIsInstantApp
4224                            || canViewInstantApps
4225                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4226                                    UserHandle.getAppId(callingUid), ps.appId);
4227                }
4228                out[i] = translateName ? cur : names[i];
4229            }
4230        }
4231        return out;
4232    }
4233
4234    @Override
4235    public int getPackageUid(String packageName, int flags, int userId) {
4236        if (!sUserManager.exists(userId)) return -1;
4237        final int callingUid = Binder.getCallingUid();
4238        flags = updateFlagsForPackage(flags, userId, packageName);
4239        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4240                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4241
4242        // reader
4243        synchronized (mPackages) {
4244            final PackageParser.Package p = mPackages.get(packageName);
4245            if (p != null && p.isMatch(flags)) {
4246                PackageSetting ps = (PackageSetting) p.mExtras;
4247                if (filterAppAccessLPr(ps, callingUid, userId)) {
4248                    return -1;
4249                }
4250                return UserHandle.getUid(userId, p.applicationInfo.uid);
4251            }
4252            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4253                final PackageSetting ps = mSettings.mPackages.get(packageName);
4254                if (ps != null && ps.isMatch(flags)
4255                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4256                    return UserHandle.getUid(userId, ps.appId);
4257                }
4258            }
4259        }
4260
4261        return -1;
4262    }
4263
4264    @Override
4265    public int[] getPackageGids(String packageName, int flags, int userId) {
4266        if (!sUserManager.exists(userId)) return null;
4267        final int callingUid = Binder.getCallingUid();
4268        flags = updateFlagsForPackage(flags, userId, packageName);
4269        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4270                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4271
4272        // reader
4273        synchronized (mPackages) {
4274            final PackageParser.Package p = mPackages.get(packageName);
4275            if (p != null && p.isMatch(flags)) {
4276                PackageSetting ps = (PackageSetting) p.mExtras;
4277                if (filterAppAccessLPr(ps, callingUid, userId)) {
4278                    return null;
4279                }
4280                // TODO: Shouldn't this be checking for package installed state for userId and
4281                // return null?
4282                return ps.getPermissionsState().computeGids(userId);
4283            }
4284            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4285                final PackageSetting ps = mSettings.mPackages.get(packageName);
4286                if (ps != null && ps.isMatch(flags)
4287                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4288                    return ps.getPermissionsState().computeGids(userId);
4289                }
4290            }
4291        }
4292
4293        return null;
4294    }
4295
4296    @Override
4297    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4298        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4299    }
4300
4301    @Override
4302    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4303            int flags) {
4304        final List<PermissionInfo> permissionList =
4305                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4306        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4307    }
4308
4309    @Override
4310    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4311        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4312    }
4313
4314    @Override
4315    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4316        final List<PermissionGroupInfo> permissionList =
4317                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4318        return (permissionList == null)
4319                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4320    }
4321
4322    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4323            int filterCallingUid, int userId) {
4324        if (!sUserManager.exists(userId)) return null;
4325        PackageSetting ps = mSettings.mPackages.get(packageName);
4326        if (ps != null) {
4327            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4328                return null;
4329            }
4330            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4331                return null;
4332            }
4333            if (ps.pkg == null) {
4334                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4335                if (pInfo != null) {
4336                    return pInfo.applicationInfo;
4337                }
4338                return null;
4339            }
4340            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4341                    ps.readUserState(userId), userId);
4342            if (ai != null) {
4343                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4344            }
4345            return ai;
4346        }
4347        return null;
4348    }
4349
4350    @Override
4351    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4352        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4353    }
4354
4355    /**
4356     * Important: The provided filterCallingUid is used exclusively to filter out applications
4357     * that can be seen based on user state. It's typically the original caller uid prior
4358     * to clearing. Because it can only be provided by trusted code, it's value can be
4359     * trusted and will be used as-is; unlike userId which will be validated by this method.
4360     */
4361    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4362            int filterCallingUid, int userId) {
4363        if (!sUserManager.exists(userId)) return null;
4364        flags = updateFlagsForApplication(flags, userId, packageName);
4365        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4366                false /* requireFullPermission */, false /* checkShell */, "get application info");
4367
4368        // writer
4369        synchronized (mPackages) {
4370            // Normalize package name to handle renamed packages and static libs
4371            packageName = resolveInternalPackageNameLPr(packageName,
4372                    PackageManager.VERSION_CODE_HIGHEST);
4373
4374            PackageParser.Package p = mPackages.get(packageName);
4375            if (DEBUG_PACKAGE_INFO) Log.v(
4376                    TAG, "getApplicationInfo " + packageName
4377                    + ": " + p);
4378            if (p != null) {
4379                PackageSetting ps = mSettings.mPackages.get(packageName);
4380                if (ps == null) return null;
4381                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4382                    return null;
4383                }
4384                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4385                    return null;
4386                }
4387                // Note: isEnabledLP() does not apply here - always return info
4388                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4389                        p, flags, ps.readUserState(userId), userId);
4390                if (ai != null) {
4391                    ai.packageName = resolveExternalPackageNameLPr(p);
4392                }
4393                return ai;
4394            }
4395            if ("android".equals(packageName)||"system".equals(packageName)) {
4396                return mAndroidApplication;
4397            }
4398            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4399                // Already generates the external package name
4400                return generateApplicationInfoFromSettingsLPw(packageName,
4401                        flags, filterCallingUid, userId);
4402            }
4403        }
4404        return null;
4405    }
4406
4407    private String normalizePackageNameLPr(String packageName) {
4408        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4409        return normalizedPackageName != null ? normalizedPackageName : packageName;
4410    }
4411
4412    @Override
4413    public void deletePreloadsFileCache() {
4414        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4415            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4416        }
4417        File dir = Environment.getDataPreloadsFileCacheDirectory();
4418        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4419        FileUtils.deleteContents(dir);
4420    }
4421
4422    @Override
4423    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4424            final int storageFlags, final IPackageDataObserver observer) {
4425        mContext.enforceCallingOrSelfPermission(
4426                android.Manifest.permission.CLEAR_APP_CACHE, null);
4427        mHandler.post(() -> {
4428            boolean success = false;
4429            try {
4430                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4431                success = true;
4432            } catch (IOException e) {
4433                Slog.w(TAG, e);
4434            }
4435            if (observer != null) {
4436                try {
4437                    observer.onRemoveCompleted(null, success);
4438                } catch (RemoteException e) {
4439                    Slog.w(TAG, e);
4440                }
4441            }
4442        });
4443    }
4444
4445    @Override
4446    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4447            final int storageFlags, final IntentSender pi) {
4448        mContext.enforceCallingOrSelfPermission(
4449                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4450        mHandler.post(() -> {
4451            boolean success = false;
4452            try {
4453                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4454                success = true;
4455            } catch (IOException e) {
4456                Slog.w(TAG, e);
4457            }
4458            if (pi != null) {
4459                try {
4460                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4461                } catch (SendIntentException e) {
4462                    Slog.w(TAG, e);
4463                }
4464            }
4465        });
4466    }
4467
4468    /**
4469     * Blocking call to clear various types of cached data across the system
4470     * until the requested bytes are available.
4471     */
4472    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4473        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4474        final File file = storage.findPathForUuid(volumeUuid);
4475        if (file.getUsableSpace() >= bytes) return;
4476
4477        if (ENABLE_FREE_CACHE_V2) {
4478            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4479                    volumeUuid);
4480            final boolean aggressive = (storageFlags
4481                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4482            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4483
4484            // 1. Pre-flight to determine if we have any chance to succeed
4485            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4486            if (internalVolume && (aggressive || SystemProperties
4487                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4488                deletePreloadsFileCache();
4489                if (file.getUsableSpace() >= bytes) return;
4490            }
4491
4492            // 3. Consider parsed APK data (aggressive only)
4493            if (internalVolume && aggressive) {
4494                FileUtils.deleteContents(mCacheDir);
4495                if (file.getUsableSpace() >= bytes) return;
4496            }
4497
4498            // 4. Consider cached app data (above quotas)
4499            try {
4500                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4501                        Installer.FLAG_FREE_CACHE_V2);
4502            } catch (InstallerException ignored) {
4503            }
4504            if (file.getUsableSpace() >= bytes) return;
4505
4506            // 5. Consider shared libraries with refcount=0 and age>min cache period
4507            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4508                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4509                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4510                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4511                return;
4512            }
4513
4514            // 6. Consider dexopt output (aggressive only)
4515            // TODO: Implement
4516
4517            // 7. Consider installed instant apps unused longer than min cache period
4518            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4519                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4520                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4521                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4522                return;
4523            }
4524
4525            // 8. Consider cached app data (below quotas)
4526            try {
4527                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4528                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4529            } catch (InstallerException ignored) {
4530            }
4531            if (file.getUsableSpace() >= bytes) return;
4532
4533            // 9. Consider DropBox entries
4534            // TODO: Implement
4535
4536            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4537            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4538                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4539                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4540                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4541                return;
4542            }
4543        } else {
4544            try {
4545                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4546            } catch (InstallerException ignored) {
4547            }
4548            if (file.getUsableSpace() >= bytes) return;
4549        }
4550
4551        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4552    }
4553
4554    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4555            throws IOException {
4556        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4557        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4558
4559        List<VersionedPackage> packagesToDelete = null;
4560        final long now = System.currentTimeMillis();
4561
4562        synchronized (mPackages) {
4563            final int[] allUsers = sUserManager.getUserIds();
4564            final int libCount = mSharedLibraries.size();
4565            for (int i = 0; i < libCount; i++) {
4566                final LongSparseArray<SharedLibraryEntry> versionedLib
4567                        = mSharedLibraries.valueAt(i);
4568                if (versionedLib == null) {
4569                    continue;
4570                }
4571                final int versionCount = versionedLib.size();
4572                for (int j = 0; j < versionCount; j++) {
4573                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4574                    // Skip packages that are not static shared libs.
4575                    if (!libInfo.isStatic()) {
4576                        break;
4577                    }
4578                    // Important: We skip static shared libs used for some user since
4579                    // in such a case we need to keep the APK on the device. The check for
4580                    // a lib being used for any user is performed by the uninstall call.
4581                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4582                    // Resolve the package name - we use synthetic package names internally
4583                    final String internalPackageName = resolveInternalPackageNameLPr(
4584                            declaringPackage.getPackageName(),
4585                            declaringPackage.getLongVersionCode());
4586                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4587                    // Skip unused static shared libs cached less than the min period
4588                    // to prevent pruning a lib needed by a subsequently installed package.
4589                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4590                        continue;
4591                    }
4592                    if (packagesToDelete == null) {
4593                        packagesToDelete = new ArrayList<>();
4594                    }
4595                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4596                            declaringPackage.getLongVersionCode()));
4597                }
4598            }
4599        }
4600
4601        if (packagesToDelete != null) {
4602            final int packageCount = packagesToDelete.size();
4603            for (int i = 0; i < packageCount; i++) {
4604                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4605                // Delete the package synchronously (will fail of the lib used for any user).
4606                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4607                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4608                                == PackageManager.DELETE_SUCCEEDED) {
4609                    if (volume.getUsableSpace() >= neededSpace) {
4610                        return true;
4611                    }
4612                }
4613            }
4614        }
4615
4616        return false;
4617    }
4618
4619    /**
4620     * Update given flags based on encryption status of current user.
4621     */
4622    private int updateFlags(int flags, int userId) {
4623        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4624                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4625            // Caller expressed an explicit opinion about what encryption
4626            // aware/unaware components they want to see, so fall through and
4627            // give them what they want
4628        } else {
4629            // Caller expressed no opinion, so match based on user state
4630            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4631                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4632            } else {
4633                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4634            }
4635        }
4636        return flags;
4637    }
4638
4639    private UserManagerInternal getUserManagerInternal() {
4640        if (mUserManagerInternal == null) {
4641            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4642        }
4643        return mUserManagerInternal;
4644    }
4645
4646    private ActivityManagerInternal getActivityManagerInternal() {
4647        if (mActivityManagerInternal == null) {
4648            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4649        }
4650        return mActivityManagerInternal;
4651    }
4652
4653
4654    private DeviceIdleController.LocalService getDeviceIdleController() {
4655        if (mDeviceIdleController == null) {
4656            mDeviceIdleController =
4657                    LocalServices.getService(DeviceIdleController.LocalService.class);
4658        }
4659        return mDeviceIdleController;
4660    }
4661
4662    /**
4663     * Update given flags when being used to request {@link PackageInfo}.
4664     */
4665    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4666        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4667        boolean triaged = true;
4668        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4669                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4670            // Caller is asking for component details, so they'd better be
4671            // asking for specific encryption matching behavior, or be triaged
4672            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4673                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4674                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4675                triaged = false;
4676            }
4677        }
4678        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4679                | PackageManager.MATCH_SYSTEM_ONLY
4680                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4681            triaged = false;
4682        }
4683        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4684            mPermissionManager.enforceCrossUserPermission(
4685                    Binder.getCallingUid(), userId, false, false,
4686                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4687                    + Debug.getCallers(5));
4688        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4689                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4690            // If the caller wants all packages and has a restricted profile associated with it,
4691            // then match all users. This is to make sure that launchers that need to access work
4692            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4693            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4694            flags |= PackageManager.MATCH_ANY_USER;
4695        }
4696        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4697            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4698                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4699        }
4700        return updateFlags(flags, userId);
4701    }
4702
4703    /**
4704     * Update given flags when being used to request {@link ApplicationInfo}.
4705     */
4706    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4707        return updateFlagsForPackage(flags, userId, cookie);
4708    }
4709
4710    /**
4711     * Update given flags when being used to request {@link ComponentInfo}.
4712     */
4713    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4714        if (cookie instanceof Intent) {
4715            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4716                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4717            }
4718        }
4719
4720        boolean triaged = true;
4721        // Caller is asking for component details, so they'd better be
4722        // asking for specific encryption matching behavior, or be triaged
4723        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4724                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4725                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4726            triaged = false;
4727        }
4728        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4729            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4730                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4731        }
4732
4733        return updateFlags(flags, userId);
4734    }
4735
4736    /**
4737     * Update given intent when being used to request {@link ResolveInfo}.
4738     */
4739    private Intent updateIntentForResolve(Intent intent) {
4740        if (intent.getSelector() != null) {
4741            intent = intent.getSelector();
4742        }
4743        if (DEBUG_PREFERRED) {
4744            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4745        }
4746        return intent;
4747    }
4748
4749    /**
4750     * Update given flags when being used to request {@link ResolveInfo}.
4751     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4752     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4753     * flag set. However, this flag is only honoured in three circumstances:
4754     * <ul>
4755     * <li>when called from a system process</li>
4756     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4757     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4758     * action and a {@code android.intent.category.BROWSABLE} category</li>
4759     * </ul>
4760     */
4761    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4762        return updateFlagsForResolve(flags, userId, intent, callingUid,
4763                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4764    }
4765    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4766            boolean wantInstantApps) {
4767        return updateFlagsForResolve(flags, userId, intent, callingUid,
4768                wantInstantApps, false /*onlyExposedExplicitly*/);
4769    }
4770    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4771            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4772        // Safe mode means we shouldn't match any third-party components
4773        if (mSafeMode) {
4774            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4775        }
4776        if (getInstantAppPackageName(callingUid) != null) {
4777            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4778            if (onlyExposedExplicitly) {
4779                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4780            }
4781            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4782            flags |= PackageManager.MATCH_INSTANT;
4783        } else {
4784            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4785            final boolean allowMatchInstant = wantInstantApps
4786                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4787            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4788                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4789            if (!allowMatchInstant) {
4790                flags &= ~PackageManager.MATCH_INSTANT;
4791            }
4792        }
4793        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4794    }
4795
4796    @Override
4797    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4798        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4799    }
4800
4801    /**
4802     * Important: The provided filterCallingUid is used exclusively to filter out activities
4803     * that can be seen based on user state. It's typically the original caller uid prior
4804     * to clearing. Because it can only be provided by trusted code, it's value can be
4805     * trusted and will be used as-is; unlike userId which will be validated by this method.
4806     */
4807    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4808            int filterCallingUid, int userId) {
4809        if (!sUserManager.exists(userId)) return null;
4810        flags = updateFlagsForComponent(flags, userId, component);
4811
4812        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4813            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4814                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4815        }
4816
4817        synchronized (mPackages) {
4818            PackageParser.Activity a = mActivities.mActivities.get(component);
4819
4820            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4821            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4822                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4823                if (ps == null) return null;
4824                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4825                    return null;
4826                }
4827                return PackageParser.generateActivityInfo(
4828                        a, flags, ps.readUserState(userId), userId);
4829            }
4830            if (mResolveComponentName.equals(component)) {
4831                return PackageParser.generateActivityInfo(
4832                        mResolveActivity, flags, new PackageUserState(), userId);
4833            }
4834        }
4835        return null;
4836    }
4837
4838    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4839        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4840            return false;
4841        }
4842        final long token = Binder.clearCallingIdentity();
4843        try {
4844            final int callingUserId = UserHandle.getUserId(callingUid);
4845            if (ActivityManager.getCurrentUser() != callingUserId) {
4846                return false;
4847            }
4848            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4849        } finally {
4850            Binder.restoreCallingIdentity(token);
4851        }
4852    }
4853
4854    @Override
4855    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4856            String resolvedType) {
4857        synchronized (mPackages) {
4858            if (component.equals(mResolveComponentName)) {
4859                // The resolver supports EVERYTHING!
4860                return true;
4861            }
4862            final int callingUid = Binder.getCallingUid();
4863            final int callingUserId = UserHandle.getUserId(callingUid);
4864            PackageParser.Activity a = mActivities.mActivities.get(component);
4865            if (a == null) {
4866                return false;
4867            }
4868            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4869            if (ps == null) {
4870                return false;
4871            }
4872            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4873                return false;
4874            }
4875            for (int i=0; i<a.intents.size(); i++) {
4876                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4877                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4878                    return true;
4879                }
4880            }
4881            return false;
4882        }
4883    }
4884
4885    @Override
4886    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4887        if (!sUserManager.exists(userId)) return null;
4888        final int callingUid = Binder.getCallingUid();
4889        flags = updateFlagsForComponent(flags, userId, component);
4890        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4891                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4892        synchronized (mPackages) {
4893            PackageParser.Activity a = mReceivers.mActivities.get(component);
4894            if (DEBUG_PACKAGE_INFO) Log.v(
4895                TAG, "getReceiverInfo " + component + ": " + a);
4896            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4897                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4898                if (ps == null) return null;
4899                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4900                    return null;
4901                }
4902                return PackageParser.generateActivityInfo(
4903                        a, flags, ps.readUserState(userId), userId);
4904            }
4905        }
4906        return null;
4907    }
4908
4909    @Override
4910    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4911            int flags, int userId) {
4912        if (!sUserManager.exists(userId)) return null;
4913        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4914        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4915            return null;
4916        }
4917
4918        flags = updateFlagsForPackage(flags, userId, null);
4919
4920        final boolean canSeeStaticLibraries =
4921                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4922                        == PERMISSION_GRANTED
4923                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4924                        == PERMISSION_GRANTED
4925                || canRequestPackageInstallsInternal(packageName,
4926                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4927                        false  /* throwIfPermNotDeclared*/)
4928                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4929                        == PERMISSION_GRANTED;
4930
4931        synchronized (mPackages) {
4932            List<SharedLibraryInfo> result = null;
4933
4934            final int libCount = mSharedLibraries.size();
4935            for (int i = 0; i < libCount; i++) {
4936                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4937                if (versionedLib == null) {
4938                    continue;
4939                }
4940
4941                final int versionCount = versionedLib.size();
4942                for (int j = 0; j < versionCount; j++) {
4943                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4944                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4945                        break;
4946                    }
4947                    final long identity = Binder.clearCallingIdentity();
4948                    try {
4949                        PackageInfo packageInfo = getPackageInfoVersioned(
4950                                libInfo.getDeclaringPackage(), flags
4951                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4952                        if (packageInfo == null) {
4953                            continue;
4954                        }
4955                    } finally {
4956                        Binder.restoreCallingIdentity(identity);
4957                    }
4958
4959                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4960                            libInfo.getLongVersion(), libInfo.getType(),
4961                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4962                            flags, userId));
4963
4964                    if (result == null) {
4965                        result = new ArrayList<>();
4966                    }
4967                    result.add(resLibInfo);
4968                }
4969            }
4970
4971            return result != null ? new ParceledListSlice<>(result) : null;
4972        }
4973    }
4974
4975    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4976            SharedLibraryInfo libInfo, int flags, int userId) {
4977        List<VersionedPackage> versionedPackages = null;
4978        final int packageCount = mSettings.mPackages.size();
4979        for (int i = 0; i < packageCount; i++) {
4980            PackageSetting ps = mSettings.mPackages.valueAt(i);
4981
4982            if (ps == null) {
4983                continue;
4984            }
4985
4986            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4987                continue;
4988            }
4989
4990            final String libName = libInfo.getName();
4991            if (libInfo.isStatic()) {
4992                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4993                if (libIdx < 0) {
4994                    continue;
4995                }
4996                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
4997                    continue;
4998                }
4999                if (versionedPackages == null) {
5000                    versionedPackages = new ArrayList<>();
5001                }
5002                // If the dependent is a static shared lib, use the public package name
5003                String dependentPackageName = ps.name;
5004                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5005                    dependentPackageName = ps.pkg.manifestPackageName;
5006                }
5007                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5008            } else if (ps.pkg != null) {
5009                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5010                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5011                    if (versionedPackages == null) {
5012                        versionedPackages = new ArrayList<>();
5013                    }
5014                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5015                }
5016            }
5017        }
5018
5019        return versionedPackages;
5020    }
5021
5022    @Override
5023    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5024        if (!sUserManager.exists(userId)) return null;
5025        final int callingUid = Binder.getCallingUid();
5026        flags = updateFlagsForComponent(flags, userId, component);
5027        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5028                false /* requireFullPermission */, false /* checkShell */, "get service info");
5029        synchronized (mPackages) {
5030            PackageParser.Service s = mServices.mServices.get(component);
5031            if (DEBUG_PACKAGE_INFO) Log.v(
5032                TAG, "getServiceInfo " + component + ": " + s);
5033            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5034                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5035                if (ps == null) return null;
5036                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5037                    return null;
5038                }
5039                return PackageParser.generateServiceInfo(
5040                        s, flags, ps.readUserState(userId), userId);
5041            }
5042        }
5043        return null;
5044    }
5045
5046    @Override
5047    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5048        if (!sUserManager.exists(userId)) return null;
5049        final int callingUid = Binder.getCallingUid();
5050        flags = updateFlagsForComponent(flags, userId, component);
5051        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5052                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5053        synchronized (mPackages) {
5054            PackageParser.Provider p = mProviders.mProviders.get(component);
5055            if (DEBUG_PACKAGE_INFO) Log.v(
5056                TAG, "getProviderInfo " + component + ": " + p);
5057            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5058                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5059                if (ps == null) return null;
5060                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5061                    return null;
5062                }
5063                return PackageParser.generateProviderInfo(
5064                        p, flags, ps.readUserState(userId), userId);
5065            }
5066        }
5067        return null;
5068    }
5069
5070    @Override
5071    public String[] getSystemSharedLibraryNames() {
5072        // allow instant applications
5073        synchronized (mPackages) {
5074            Set<String> libs = null;
5075            final int libCount = mSharedLibraries.size();
5076            for (int i = 0; i < libCount; i++) {
5077                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5078                if (versionedLib == null) {
5079                    continue;
5080                }
5081                final int versionCount = versionedLib.size();
5082                for (int j = 0; j < versionCount; j++) {
5083                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5084                    if (!libEntry.info.isStatic()) {
5085                        if (libs == null) {
5086                            libs = new ArraySet<>();
5087                        }
5088                        libs.add(libEntry.info.getName());
5089                        break;
5090                    }
5091                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5092                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5093                            UserHandle.getUserId(Binder.getCallingUid()),
5094                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5095                        if (libs == null) {
5096                            libs = new ArraySet<>();
5097                        }
5098                        libs.add(libEntry.info.getName());
5099                        break;
5100                    }
5101                }
5102            }
5103
5104            if (libs != null) {
5105                String[] libsArray = new String[libs.size()];
5106                libs.toArray(libsArray);
5107                return libsArray;
5108            }
5109
5110            return null;
5111        }
5112    }
5113
5114    @Override
5115    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5116        // allow instant applications
5117        synchronized (mPackages) {
5118            return mServicesSystemSharedLibraryPackageName;
5119        }
5120    }
5121
5122    @Override
5123    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5124        // allow instant applications
5125        synchronized (mPackages) {
5126            return mSharedSystemSharedLibraryPackageName;
5127        }
5128    }
5129
5130    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5131        for (int i = userList.length - 1; i >= 0; --i) {
5132            final int userId = userList[i];
5133            // don't add instant app to the list of updates
5134            if (pkgSetting.getInstantApp(userId)) {
5135                continue;
5136            }
5137            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5138            if (changedPackages == null) {
5139                changedPackages = new SparseArray<>();
5140                mChangedPackages.put(userId, changedPackages);
5141            }
5142            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5143            if (sequenceNumbers == null) {
5144                sequenceNumbers = new HashMap<>();
5145                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5146            }
5147            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5148            if (sequenceNumber != null) {
5149                changedPackages.remove(sequenceNumber);
5150            }
5151            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5152            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5153        }
5154        mChangedPackagesSequenceNumber++;
5155    }
5156
5157    @Override
5158    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5159        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5160            return null;
5161        }
5162        synchronized (mPackages) {
5163            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5164                return null;
5165            }
5166            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5167            if (changedPackages == null) {
5168                return null;
5169            }
5170            final List<String> packageNames =
5171                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5172            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5173                final String packageName = changedPackages.get(i);
5174                if (packageName != null) {
5175                    packageNames.add(packageName);
5176                }
5177            }
5178            return packageNames.isEmpty()
5179                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5180        }
5181    }
5182
5183    @Override
5184    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5185        // allow instant applications
5186        ArrayList<FeatureInfo> res;
5187        synchronized (mAvailableFeatures) {
5188            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5189            res.addAll(mAvailableFeatures.values());
5190        }
5191        final FeatureInfo fi = new FeatureInfo();
5192        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5193                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5194        res.add(fi);
5195
5196        return new ParceledListSlice<>(res);
5197    }
5198
5199    @Override
5200    public boolean hasSystemFeature(String name, int version) {
5201        // allow instant applications
5202        synchronized (mAvailableFeatures) {
5203            final FeatureInfo feat = mAvailableFeatures.get(name);
5204            if (feat == null) {
5205                return false;
5206            } else {
5207                return feat.version >= version;
5208            }
5209        }
5210    }
5211
5212    @Override
5213    public int checkPermission(String permName, String pkgName, int userId) {
5214        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5215    }
5216
5217    @Override
5218    public int checkUidPermission(String permName, int uid) {
5219        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5220    }
5221
5222    @Override
5223    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5224        if (UserHandle.getCallingUserId() != userId) {
5225            mContext.enforceCallingPermission(
5226                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5227                    "isPermissionRevokedByPolicy for user " + userId);
5228        }
5229
5230        if (checkPermission(permission, packageName, userId)
5231                == PackageManager.PERMISSION_GRANTED) {
5232            return false;
5233        }
5234
5235        final int callingUid = Binder.getCallingUid();
5236        if (getInstantAppPackageName(callingUid) != null) {
5237            if (!isCallerSameApp(packageName, callingUid)) {
5238                return false;
5239            }
5240        } else {
5241            if (isInstantApp(packageName, userId)) {
5242                return false;
5243            }
5244        }
5245
5246        final long identity = Binder.clearCallingIdentity();
5247        try {
5248            final int flags = getPermissionFlags(permission, packageName, userId);
5249            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5250        } finally {
5251            Binder.restoreCallingIdentity(identity);
5252        }
5253    }
5254
5255    @Override
5256    public String getPermissionControllerPackageName() {
5257        synchronized (mPackages) {
5258            return mRequiredInstallerPackage;
5259        }
5260    }
5261
5262    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5263        return mPermissionManager.addDynamicPermission(
5264                info, async, getCallingUid(), new PermissionCallback() {
5265                    @Override
5266                    public void onPermissionChanged() {
5267                        if (!async) {
5268                            mSettings.writeLPr();
5269                        } else {
5270                            scheduleWriteSettingsLocked();
5271                        }
5272                    }
5273                });
5274    }
5275
5276    @Override
5277    public boolean addPermission(PermissionInfo info) {
5278        synchronized (mPackages) {
5279            return addDynamicPermission(info, false);
5280        }
5281    }
5282
5283    @Override
5284    public boolean addPermissionAsync(PermissionInfo info) {
5285        synchronized (mPackages) {
5286            return addDynamicPermission(info, true);
5287        }
5288    }
5289
5290    @Override
5291    public void removePermission(String permName) {
5292        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5293    }
5294
5295    @Override
5296    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5297        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5298                getCallingUid(), userId, mPermissionCallback);
5299    }
5300
5301    @Override
5302    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5303        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5304                getCallingUid(), userId, mPermissionCallback);
5305    }
5306
5307    @Override
5308    public void resetRuntimePermissions() {
5309        mContext.enforceCallingOrSelfPermission(
5310                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5311                "revokeRuntimePermission");
5312
5313        int callingUid = Binder.getCallingUid();
5314        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5315            mContext.enforceCallingOrSelfPermission(
5316                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5317                    "resetRuntimePermissions");
5318        }
5319
5320        synchronized (mPackages) {
5321            mPermissionManager.updateAllPermissions(
5322                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5323                    mPermissionCallback);
5324            for (int userId : UserManagerService.getInstance().getUserIds()) {
5325                final int packageCount = mPackages.size();
5326                for (int i = 0; i < packageCount; i++) {
5327                    PackageParser.Package pkg = mPackages.valueAt(i);
5328                    if (!(pkg.mExtras instanceof PackageSetting)) {
5329                        continue;
5330                    }
5331                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5332                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5333                }
5334            }
5335        }
5336    }
5337
5338    @Override
5339    public int getPermissionFlags(String permName, String packageName, int userId) {
5340        return mPermissionManager.getPermissionFlags(
5341                permName, packageName, getCallingUid(), userId);
5342    }
5343
5344    @Override
5345    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5346            int flagValues, int userId) {
5347        mPermissionManager.updatePermissionFlags(
5348                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5349                mPermissionCallback);
5350    }
5351
5352    /**
5353     * Update the permission flags for all packages and runtime permissions of a user in order
5354     * to allow device or profile owner to remove POLICY_FIXED.
5355     */
5356    @Override
5357    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5358        synchronized (mPackages) {
5359            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5360                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5361                    mPermissionCallback);
5362            if (changed) {
5363                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5364            }
5365        }
5366    }
5367
5368    @Override
5369    public boolean shouldShowRequestPermissionRationale(String permissionName,
5370            String packageName, int userId) {
5371        if (UserHandle.getCallingUserId() != userId) {
5372            mContext.enforceCallingPermission(
5373                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5374                    "canShowRequestPermissionRationale for user " + userId);
5375        }
5376
5377        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5378        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5379            return false;
5380        }
5381
5382        if (checkPermission(permissionName, packageName, userId)
5383                == PackageManager.PERMISSION_GRANTED) {
5384            return false;
5385        }
5386
5387        final int flags;
5388
5389        final long identity = Binder.clearCallingIdentity();
5390        try {
5391            flags = getPermissionFlags(permissionName,
5392                    packageName, userId);
5393        } finally {
5394            Binder.restoreCallingIdentity(identity);
5395        }
5396
5397        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5398                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5399                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5400
5401        if ((flags & fixedFlags) != 0) {
5402            return false;
5403        }
5404
5405        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5406    }
5407
5408    @Override
5409    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5410        mContext.enforceCallingOrSelfPermission(
5411                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5412                "addOnPermissionsChangeListener");
5413
5414        synchronized (mPackages) {
5415            mOnPermissionChangeListeners.addListenerLocked(listener);
5416        }
5417    }
5418
5419    @Override
5420    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5421        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5422            throw new SecurityException("Instant applications don't have access to this method");
5423        }
5424        synchronized (mPackages) {
5425            mOnPermissionChangeListeners.removeListenerLocked(listener);
5426        }
5427    }
5428
5429    @Override
5430    public boolean isProtectedBroadcast(String actionName) {
5431        // allow instant applications
5432        synchronized (mProtectedBroadcasts) {
5433            if (mProtectedBroadcasts.contains(actionName)) {
5434                return true;
5435            } else if (actionName != null) {
5436                // TODO: remove these terrible hacks
5437                if (actionName.startsWith("android.net.netmon.lingerExpired")
5438                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5439                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5440                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5441                    return true;
5442                }
5443            }
5444        }
5445        return false;
5446    }
5447
5448    @Override
5449    public int checkSignatures(String pkg1, String pkg2) {
5450        synchronized (mPackages) {
5451            final PackageParser.Package p1 = mPackages.get(pkg1);
5452            final PackageParser.Package p2 = mPackages.get(pkg2);
5453            if (p1 == null || p1.mExtras == null
5454                    || p2 == null || p2.mExtras == null) {
5455                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5456            }
5457            final int callingUid = Binder.getCallingUid();
5458            final int callingUserId = UserHandle.getUserId(callingUid);
5459            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5460            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5461            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5462                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5463                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5464            }
5465            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5466        }
5467    }
5468
5469    @Override
5470    public int checkUidSignatures(int uid1, int uid2) {
5471        final int callingUid = Binder.getCallingUid();
5472        final int callingUserId = UserHandle.getUserId(callingUid);
5473        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5474        // Map to base uids.
5475        uid1 = UserHandle.getAppId(uid1);
5476        uid2 = UserHandle.getAppId(uid2);
5477        // reader
5478        synchronized (mPackages) {
5479            Signature[] s1;
5480            Signature[] s2;
5481            Object obj = mSettings.getUserIdLPr(uid1);
5482            if (obj != null) {
5483                if (obj instanceof SharedUserSetting) {
5484                    if (isCallerInstantApp) {
5485                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5486                    }
5487                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5488                } else if (obj instanceof PackageSetting) {
5489                    final PackageSetting ps = (PackageSetting) obj;
5490                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5491                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5492                    }
5493                    s1 = ps.signatures.mSigningDetails.signatures;
5494                } else {
5495                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5496                }
5497            } else {
5498                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5499            }
5500            obj = mSettings.getUserIdLPr(uid2);
5501            if (obj != null) {
5502                if (obj instanceof SharedUserSetting) {
5503                    if (isCallerInstantApp) {
5504                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5505                    }
5506                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5507                } else if (obj instanceof PackageSetting) {
5508                    final PackageSetting ps = (PackageSetting) obj;
5509                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5510                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5511                    }
5512                    s2 = ps.signatures.mSigningDetails.signatures;
5513                } else {
5514                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5515                }
5516            } else {
5517                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5518            }
5519            return compareSignatures(s1, s2);
5520        }
5521    }
5522
5523    @Override
5524    public boolean hasSigningCertificate(
5525            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5526
5527        synchronized (mPackages) {
5528            final PackageParser.Package p = mPackages.get(packageName);
5529            if (p == null || p.mExtras == null) {
5530                return false;
5531            }
5532            final int callingUid = Binder.getCallingUid();
5533            final int callingUserId = UserHandle.getUserId(callingUid);
5534            final PackageSetting ps = (PackageSetting) p.mExtras;
5535            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5536                return false;
5537            }
5538            switch (type) {
5539                case CERT_INPUT_RAW_X509:
5540                    return p.mSigningDetails.hasCertificate(certificate);
5541                case CERT_INPUT_SHA256:
5542                    return p.mSigningDetails.hasSha256Certificate(certificate);
5543                default:
5544                    return false;
5545            }
5546        }
5547    }
5548
5549    @Override
5550    public boolean hasUidSigningCertificate(
5551            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5552        final int callingUid = Binder.getCallingUid();
5553        final int callingUserId = UserHandle.getUserId(callingUid);
5554        // Map to base uids.
5555        uid = UserHandle.getAppId(uid);
5556        // reader
5557        synchronized (mPackages) {
5558            final PackageParser.SigningDetails signingDetails;
5559            final Object obj = mSettings.getUserIdLPr(uid);
5560            if (obj != null) {
5561                if (obj instanceof SharedUserSetting) {
5562                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5563                    if (isCallerInstantApp) {
5564                        return false;
5565                    }
5566                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5567                } else if (obj instanceof PackageSetting) {
5568                    final PackageSetting ps = (PackageSetting) obj;
5569                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5570                        return false;
5571                    }
5572                    signingDetails = ps.signatures.mSigningDetails;
5573                } else {
5574                    return false;
5575                }
5576            } else {
5577                return false;
5578            }
5579            switch (type) {
5580                case CERT_INPUT_RAW_X509:
5581                    return signingDetails.hasCertificate(certificate);
5582                case CERT_INPUT_SHA256:
5583                    return signingDetails.hasSha256Certificate(certificate);
5584                default:
5585                    return false;
5586            }
5587        }
5588    }
5589
5590    /**
5591     * This method should typically only be used when granting or revoking
5592     * permissions, since the app may immediately restart after this call.
5593     * <p>
5594     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5595     * guard your work against the app being relaunched.
5596     */
5597    private void killUid(int appId, int userId, String reason) {
5598        final long identity = Binder.clearCallingIdentity();
5599        try {
5600            IActivityManager am = ActivityManager.getService();
5601            if (am != null) {
5602                try {
5603                    am.killUid(appId, userId, reason);
5604                } catch (RemoteException e) {
5605                    /* ignore - same process */
5606                }
5607            }
5608        } finally {
5609            Binder.restoreCallingIdentity(identity);
5610        }
5611    }
5612
5613    /**
5614     * If the database version for this type of package (internal storage or
5615     * external storage) is less than the version where package signatures
5616     * were updated, return true.
5617     */
5618    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5619        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5620        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5621    }
5622
5623    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5624        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5625        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5626    }
5627
5628    @Override
5629    public List<String> getAllPackages() {
5630        final int callingUid = Binder.getCallingUid();
5631        final int callingUserId = UserHandle.getUserId(callingUid);
5632        synchronized (mPackages) {
5633            if (canViewInstantApps(callingUid, callingUserId)) {
5634                return new ArrayList<String>(mPackages.keySet());
5635            }
5636            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5637            final List<String> result = new ArrayList<>();
5638            if (instantAppPkgName != null) {
5639                // caller is an instant application; filter unexposed applications
5640                for (PackageParser.Package pkg : mPackages.values()) {
5641                    if (!pkg.visibleToInstantApps) {
5642                        continue;
5643                    }
5644                    result.add(pkg.packageName);
5645                }
5646            } else {
5647                // caller is a normal application; filter instant applications
5648                for (PackageParser.Package pkg : mPackages.values()) {
5649                    final PackageSetting ps =
5650                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5651                    if (ps != null
5652                            && ps.getInstantApp(callingUserId)
5653                            && !mInstantAppRegistry.isInstantAccessGranted(
5654                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5655                        continue;
5656                    }
5657                    result.add(pkg.packageName);
5658                }
5659            }
5660            return result;
5661        }
5662    }
5663
5664    @Override
5665    public String[] getPackagesForUid(int uid) {
5666        final int callingUid = Binder.getCallingUid();
5667        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5668        final int userId = UserHandle.getUserId(uid);
5669        uid = UserHandle.getAppId(uid);
5670        // reader
5671        synchronized (mPackages) {
5672            Object obj = mSettings.getUserIdLPr(uid);
5673            if (obj instanceof SharedUserSetting) {
5674                if (isCallerInstantApp) {
5675                    return null;
5676                }
5677                final SharedUserSetting sus = (SharedUserSetting) obj;
5678                final int N = sus.packages.size();
5679                String[] res = new String[N];
5680                final Iterator<PackageSetting> it = sus.packages.iterator();
5681                int i = 0;
5682                while (it.hasNext()) {
5683                    PackageSetting ps = it.next();
5684                    if (ps.getInstalled(userId)) {
5685                        res[i++] = ps.name;
5686                    } else {
5687                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5688                    }
5689                }
5690                return res;
5691            } else if (obj instanceof PackageSetting) {
5692                final PackageSetting ps = (PackageSetting) obj;
5693                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5694                    return new String[]{ps.name};
5695                }
5696            }
5697        }
5698        return null;
5699    }
5700
5701    @Override
5702    public String getNameForUid(int uid) {
5703        final int callingUid = Binder.getCallingUid();
5704        if (getInstantAppPackageName(callingUid) != null) {
5705            return null;
5706        }
5707        synchronized (mPackages) {
5708            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5709            if (obj instanceof SharedUserSetting) {
5710                final SharedUserSetting sus = (SharedUserSetting) obj;
5711                return sus.name + ":" + sus.userId;
5712            } else if (obj instanceof PackageSetting) {
5713                final PackageSetting ps = (PackageSetting) obj;
5714                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5715                    return null;
5716                }
5717                return ps.name;
5718            }
5719            return null;
5720        }
5721    }
5722
5723    @Override
5724    public String[] getNamesForUids(int[] uids) {
5725        if (uids == null || uids.length == 0) {
5726            return null;
5727        }
5728        final int callingUid = Binder.getCallingUid();
5729        if (getInstantAppPackageName(callingUid) != null) {
5730            return null;
5731        }
5732        final String[] names = new String[uids.length];
5733        synchronized (mPackages) {
5734            for (int i = uids.length - 1; i >= 0; i--) {
5735                final int uid = uids[i];
5736                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5737                if (obj instanceof SharedUserSetting) {
5738                    final SharedUserSetting sus = (SharedUserSetting) obj;
5739                    names[i] = "shared:" + sus.name;
5740                } else if (obj instanceof PackageSetting) {
5741                    final PackageSetting ps = (PackageSetting) obj;
5742                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5743                        names[i] = null;
5744                    } else {
5745                        names[i] = ps.name;
5746                    }
5747                } else {
5748                    names[i] = null;
5749                }
5750            }
5751        }
5752        return names;
5753    }
5754
5755    @Override
5756    public int getUidForSharedUser(String sharedUserName) {
5757        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5758            return -1;
5759        }
5760        if (sharedUserName == null) {
5761            return -1;
5762        }
5763        // reader
5764        synchronized (mPackages) {
5765            SharedUserSetting suid;
5766            try {
5767                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5768                if (suid != null) {
5769                    return suid.userId;
5770                }
5771            } catch (PackageManagerException ignore) {
5772                // can't happen, but, still need to catch it
5773            }
5774            return -1;
5775        }
5776    }
5777
5778    @Override
5779    public int getFlagsForUid(int uid) {
5780        final int callingUid = Binder.getCallingUid();
5781        if (getInstantAppPackageName(callingUid) != null) {
5782            return 0;
5783        }
5784        synchronized (mPackages) {
5785            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5786            if (obj instanceof SharedUserSetting) {
5787                final SharedUserSetting sus = (SharedUserSetting) obj;
5788                return sus.pkgFlags;
5789            } else if (obj instanceof PackageSetting) {
5790                final PackageSetting ps = (PackageSetting) obj;
5791                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5792                    return 0;
5793                }
5794                return ps.pkgFlags;
5795            }
5796        }
5797        return 0;
5798    }
5799
5800    @Override
5801    public int getPrivateFlagsForUid(int uid) {
5802        final int callingUid = Binder.getCallingUid();
5803        if (getInstantAppPackageName(callingUid) != null) {
5804            return 0;
5805        }
5806        synchronized (mPackages) {
5807            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5808            if (obj instanceof SharedUserSetting) {
5809                final SharedUserSetting sus = (SharedUserSetting) obj;
5810                return sus.pkgPrivateFlags;
5811            } else if (obj instanceof PackageSetting) {
5812                final PackageSetting ps = (PackageSetting) obj;
5813                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5814                    return 0;
5815                }
5816                return ps.pkgPrivateFlags;
5817            }
5818        }
5819        return 0;
5820    }
5821
5822    @Override
5823    public boolean isUidPrivileged(int uid) {
5824        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5825            return false;
5826        }
5827        uid = UserHandle.getAppId(uid);
5828        // reader
5829        synchronized (mPackages) {
5830            Object obj = mSettings.getUserIdLPr(uid);
5831            if (obj instanceof SharedUserSetting) {
5832                final SharedUserSetting sus = (SharedUserSetting) obj;
5833                final Iterator<PackageSetting> it = sus.packages.iterator();
5834                while (it.hasNext()) {
5835                    if (it.next().isPrivileged()) {
5836                        return true;
5837                    }
5838                }
5839            } else if (obj instanceof PackageSetting) {
5840                final PackageSetting ps = (PackageSetting) obj;
5841                return ps.isPrivileged();
5842            }
5843        }
5844        return false;
5845    }
5846
5847    @Override
5848    public String[] getAppOpPermissionPackages(String permName) {
5849        return mPermissionManager.getAppOpPermissionPackages(permName);
5850    }
5851
5852    @Override
5853    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5854            int flags, int userId) {
5855        return resolveIntentInternal(
5856                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5857    }
5858
5859    /**
5860     * Normally instant apps can only be resolved when they're visible to the caller.
5861     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5862     * since we need to allow the system to start any installed application.
5863     */
5864    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5865            int flags, int userId, boolean resolveForStart) {
5866        try {
5867            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5868
5869            if (!sUserManager.exists(userId)) return null;
5870            final int callingUid = Binder.getCallingUid();
5871            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5872            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5873                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5874
5875            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5876            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5877                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5878            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5879
5880            final ResolveInfo bestChoice =
5881                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5882            return bestChoice;
5883        } finally {
5884            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5885        }
5886    }
5887
5888    @Override
5889    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5890        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5891            throw new SecurityException(
5892                    "findPersistentPreferredActivity can only be run by the system");
5893        }
5894        if (!sUserManager.exists(userId)) {
5895            return null;
5896        }
5897        final int callingUid = Binder.getCallingUid();
5898        intent = updateIntentForResolve(intent);
5899        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5900        final int flags = updateFlagsForResolve(
5901                0, userId, intent, callingUid, false /*includeInstantApps*/);
5902        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5903                userId);
5904        synchronized (mPackages) {
5905            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5906                    userId);
5907        }
5908    }
5909
5910    @Override
5911    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5912            IntentFilter filter, int match, ComponentName activity) {
5913        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5914            return;
5915        }
5916        final int userId = UserHandle.getCallingUserId();
5917        if (DEBUG_PREFERRED) {
5918            Log.v(TAG, "setLastChosenActivity intent=" + intent
5919                + " resolvedType=" + resolvedType
5920                + " flags=" + flags
5921                + " filter=" + filter
5922                + " match=" + match
5923                + " activity=" + activity);
5924            filter.dump(new PrintStreamPrinter(System.out), "    ");
5925        }
5926        intent.setComponent(null);
5927        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5928                userId);
5929        // Find any earlier preferred or last chosen entries and nuke them
5930        findPreferredActivity(intent, resolvedType,
5931                flags, query, 0, false, true, false, userId);
5932        // Add the new activity as the last chosen for this filter
5933        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5934                "Setting last chosen");
5935    }
5936
5937    @Override
5938    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5939        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5940            return null;
5941        }
5942        final int userId = UserHandle.getCallingUserId();
5943        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5944        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5945                userId);
5946        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5947                false, false, false, userId);
5948    }
5949
5950    /**
5951     * Returns whether or not instant apps have been disabled remotely.
5952     */
5953    private boolean isEphemeralDisabled() {
5954        return mEphemeralAppsDisabled;
5955    }
5956
5957    private boolean isInstantAppAllowed(
5958            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5959            boolean skipPackageCheck) {
5960        if (mInstantAppResolverConnection == null) {
5961            return false;
5962        }
5963        if (mInstantAppInstallerActivity == null) {
5964            return false;
5965        }
5966        if (intent.getComponent() != null) {
5967            return false;
5968        }
5969        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5970            return false;
5971        }
5972        if (!skipPackageCheck && intent.getPackage() != null) {
5973            return false;
5974        }
5975        if (!intent.isWebIntent()) {
5976            // for non web intents, we should not resolve externally if an app already exists to
5977            // handle it or if the caller didn't explicitly request it.
5978            if ((resolvedActivities != null && resolvedActivities.size() != 0)
5979                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
5980                return false;
5981            }
5982        } else if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
5983            return false;
5984        }
5985        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5986        // Or if there's already an ephemeral app installed that handles the action
5987        synchronized (mPackages) {
5988            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5989            for (int n = 0; n < count; n++) {
5990                final ResolveInfo info = resolvedActivities.get(n);
5991                final String packageName = info.activityInfo.packageName;
5992                final PackageSetting ps = mSettings.mPackages.get(packageName);
5993                if (ps != null) {
5994                    // only check domain verification status if the app is not a browser
5995                    if (!info.handleAllWebDataURI) {
5996                        // Try to get the status from User settings first
5997                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5998                        final int status = (int) (packedStatus >> 32);
5999                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6000                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6001                            if (DEBUG_INSTANT) {
6002                                Slog.v(TAG, "DENY instant app;"
6003                                    + " pkg: " + packageName + ", status: " + status);
6004                            }
6005                            return false;
6006                        }
6007                    }
6008                    if (ps.getInstantApp(userId)) {
6009                        if (DEBUG_INSTANT) {
6010                            Slog.v(TAG, "DENY instant app installed;"
6011                                    + " pkg: " + packageName);
6012                        }
6013                        return false;
6014                    }
6015                }
6016            }
6017        }
6018        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6019        return true;
6020    }
6021
6022    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6023            Intent origIntent, String resolvedType, String callingPackage,
6024            Bundle verificationBundle, int userId) {
6025        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6026                new InstantAppRequest(responseObj, origIntent, resolvedType,
6027                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6028        mHandler.sendMessage(msg);
6029    }
6030
6031    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6032            int flags, List<ResolveInfo> query, int userId) {
6033        if (query != null) {
6034            final int N = query.size();
6035            if (N == 1) {
6036                return query.get(0);
6037            } else if (N > 1) {
6038                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6039                // If there is more than one activity with the same priority,
6040                // then let the user decide between them.
6041                ResolveInfo r0 = query.get(0);
6042                ResolveInfo r1 = query.get(1);
6043                if (DEBUG_INTENT_MATCHING || debug) {
6044                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6045                            + r1.activityInfo.name + "=" + r1.priority);
6046                }
6047                // If the first activity has a higher priority, or a different
6048                // default, then it is always desirable to pick it.
6049                if (r0.priority != r1.priority
6050                        || r0.preferredOrder != r1.preferredOrder
6051                        || r0.isDefault != r1.isDefault) {
6052                    return query.get(0);
6053                }
6054                // If we have saved a preference for a preferred activity for
6055                // this Intent, use that.
6056                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6057                        flags, query, r0.priority, true, false, debug, userId);
6058                if (ri != null) {
6059                    return ri;
6060                }
6061                // If we have an ephemeral app, use it
6062                for (int i = 0; i < N; i++) {
6063                    ri = query.get(i);
6064                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6065                        final String packageName = ri.activityInfo.packageName;
6066                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6067                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6068                        final int status = (int)(packedStatus >> 32);
6069                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6070                            return ri;
6071                        }
6072                    }
6073                }
6074                ri = new ResolveInfo(mResolveInfo);
6075                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6076                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6077                // If all of the options come from the same package, show the application's
6078                // label and icon instead of the generic resolver's.
6079                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6080                // and then throw away the ResolveInfo itself, meaning that the caller loses
6081                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6082                // a fallback for this case; we only set the target package's resources on
6083                // the ResolveInfo, not the ActivityInfo.
6084                final String intentPackage = intent.getPackage();
6085                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6086                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6087                    ri.resolvePackageName = intentPackage;
6088                    if (userNeedsBadging(userId)) {
6089                        ri.noResourceId = true;
6090                    } else {
6091                        ri.icon = appi.icon;
6092                    }
6093                    ri.iconResourceId = appi.icon;
6094                    ri.labelRes = appi.labelRes;
6095                }
6096                ri.activityInfo.applicationInfo = new ApplicationInfo(
6097                        ri.activityInfo.applicationInfo);
6098                if (userId != 0) {
6099                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6100                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6101                }
6102                // Make sure that the resolver is displayable in car mode
6103                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6104                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6105                return ri;
6106            }
6107        }
6108        return null;
6109    }
6110
6111    /**
6112     * Return true if the given list is not empty and all of its contents have
6113     * an activityInfo with the given package name.
6114     */
6115    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6116        if (ArrayUtils.isEmpty(list)) {
6117            return false;
6118        }
6119        for (int i = 0, N = list.size(); i < N; i++) {
6120            final ResolveInfo ri = list.get(i);
6121            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6122            if (ai == null || !packageName.equals(ai.packageName)) {
6123                return false;
6124            }
6125        }
6126        return true;
6127    }
6128
6129    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6130            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6131        final int N = query.size();
6132        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6133                .get(userId);
6134        // Get the list of persistent preferred activities that handle the intent
6135        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6136        List<PersistentPreferredActivity> pprefs = ppir != null
6137                ? ppir.queryIntent(intent, resolvedType,
6138                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6139                        userId)
6140                : null;
6141        if (pprefs != null && pprefs.size() > 0) {
6142            final int M = pprefs.size();
6143            for (int i=0; i<M; i++) {
6144                final PersistentPreferredActivity ppa = pprefs.get(i);
6145                if (DEBUG_PREFERRED || debug) {
6146                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6147                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6148                            + "\n  component=" + ppa.mComponent);
6149                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6150                }
6151                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6152                        flags | MATCH_DISABLED_COMPONENTS, userId);
6153                if (DEBUG_PREFERRED || debug) {
6154                    Slog.v(TAG, "Found persistent preferred activity:");
6155                    if (ai != null) {
6156                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6157                    } else {
6158                        Slog.v(TAG, "  null");
6159                    }
6160                }
6161                if (ai == null) {
6162                    // This previously registered persistent preferred activity
6163                    // component is no longer known. Ignore it and do NOT remove it.
6164                    continue;
6165                }
6166                for (int j=0; j<N; j++) {
6167                    final ResolveInfo ri = query.get(j);
6168                    if (!ri.activityInfo.applicationInfo.packageName
6169                            .equals(ai.applicationInfo.packageName)) {
6170                        continue;
6171                    }
6172                    if (!ri.activityInfo.name.equals(ai.name)) {
6173                        continue;
6174                    }
6175                    //  Found a persistent preference that can handle the intent.
6176                    if (DEBUG_PREFERRED || debug) {
6177                        Slog.v(TAG, "Returning persistent preferred activity: " +
6178                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6179                    }
6180                    return ri;
6181                }
6182            }
6183        }
6184        return null;
6185    }
6186
6187    // TODO: handle preferred activities missing while user has amnesia
6188    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6189            List<ResolveInfo> query, int priority, boolean always,
6190            boolean removeMatches, boolean debug, int userId) {
6191        if (!sUserManager.exists(userId)) return null;
6192        final int callingUid = Binder.getCallingUid();
6193        flags = updateFlagsForResolve(
6194                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6195        intent = updateIntentForResolve(intent);
6196        // writer
6197        synchronized (mPackages) {
6198            // Try to find a matching persistent preferred activity.
6199            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6200                    debug, userId);
6201
6202            // If a persistent preferred activity matched, use it.
6203            if (pri != null) {
6204                return pri;
6205            }
6206
6207            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6208            // Get the list of preferred activities that handle the intent
6209            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6210            List<PreferredActivity> prefs = pir != null
6211                    ? pir.queryIntent(intent, resolvedType,
6212                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6213                            userId)
6214                    : null;
6215            if (prefs != null && prefs.size() > 0) {
6216                boolean changed = false;
6217                try {
6218                    // First figure out how good the original match set is.
6219                    // We will only allow preferred activities that came
6220                    // from the same match quality.
6221                    int match = 0;
6222
6223                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6224
6225                    final int N = query.size();
6226                    for (int j=0; j<N; j++) {
6227                        final ResolveInfo ri = query.get(j);
6228                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6229                                + ": 0x" + Integer.toHexString(match));
6230                        if (ri.match > match) {
6231                            match = ri.match;
6232                        }
6233                    }
6234
6235                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6236                            + Integer.toHexString(match));
6237
6238                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6239                    final int M = prefs.size();
6240                    for (int i=0; i<M; i++) {
6241                        final PreferredActivity pa = prefs.get(i);
6242                        if (DEBUG_PREFERRED || debug) {
6243                            Slog.v(TAG, "Checking PreferredActivity ds="
6244                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6245                                    + "\n  component=" + pa.mPref.mComponent);
6246                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6247                        }
6248                        if (pa.mPref.mMatch != match) {
6249                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6250                                    + Integer.toHexString(pa.mPref.mMatch));
6251                            continue;
6252                        }
6253                        // If it's not an "always" type preferred activity and that's what we're
6254                        // looking for, skip it.
6255                        if (always && !pa.mPref.mAlways) {
6256                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6257                            continue;
6258                        }
6259                        final ActivityInfo ai = getActivityInfo(
6260                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6261                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6262                                userId);
6263                        if (DEBUG_PREFERRED || debug) {
6264                            Slog.v(TAG, "Found preferred activity:");
6265                            if (ai != null) {
6266                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6267                            } else {
6268                                Slog.v(TAG, "  null");
6269                            }
6270                        }
6271                        if (ai == null) {
6272                            // This previously registered preferred activity
6273                            // component is no longer known.  Most likely an update
6274                            // to the app was installed and in the new version this
6275                            // component no longer exists.  Clean it up by removing
6276                            // it from the preferred activities list, and skip it.
6277                            Slog.w(TAG, "Removing dangling preferred activity: "
6278                                    + pa.mPref.mComponent);
6279                            pir.removeFilter(pa);
6280                            changed = true;
6281                            continue;
6282                        }
6283                        for (int j=0; j<N; j++) {
6284                            final ResolveInfo ri = query.get(j);
6285                            if (!ri.activityInfo.applicationInfo.packageName
6286                                    .equals(ai.applicationInfo.packageName)) {
6287                                continue;
6288                            }
6289                            if (!ri.activityInfo.name.equals(ai.name)) {
6290                                continue;
6291                            }
6292
6293                            if (removeMatches) {
6294                                pir.removeFilter(pa);
6295                                changed = true;
6296                                if (DEBUG_PREFERRED) {
6297                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6298                                }
6299                                break;
6300                            }
6301
6302                            // Okay we found a previously set preferred or last chosen app.
6303                            // If the result set is different from when this
6304                            // was created, and is not a subset of the preferred set, we need to
6305                            // clear it and re-ask the user their preference, if we're looking for
6306                            // an "always" type entry.
6307                            if (always && !pa.mPref.sameSet(query)) {
6308                                if (pa.mPref.isSuperset(query)) {
6309                                    // some components of the set are no longer present in
6310                                    // the query, but the preferred activity can still be reused
6311                                    if (DEBUG_PREFERRED) {
6312                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6313                                                + " still valid as only non-preferred components"
6314                                                + " were removed for " + intent + " type "
6315                                                + resolvedType);
6316                                    }
6317                                    // remove obsolete components and re-add the up-to-date filter
6318                                    PreferredActivity freshPa = new PreferredActivity(pa,
6319                                            pa.mPref.mMatch,
6320                                            pa.mPref.discardObsoleteComponents(query),
6321                                            pa.mPref.mComponent,
6322                                            pa.mPref.mAlways);
6323                                    pir.removeFilter(pa);
6324                                    pir.addFilter(freshPa);
6325                                    changed = true;
6326                                } else {
6327                                    Slog.i(TAG,
6328                                            "Result set changed, dropping preferred activity for "
6329                                                    + intent + " type " + resolvedType);
6330                                    if (DEBUG_PREFERRED) {
6331                                        Slog.v(TAG, "Removing preferred activity since set changed "
6332                                                + pa.mPref.mComponent);
6333                                    }
6334                                    pir.removeFilter(pa);
6335                                    // Re-add the filter as a "last chosen" entry (!always)
6336                                    PreferredActivity lastChosen = new PreferredActivity(
6337                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6338                                    pir.addFilter(lastChosen);
6339                                    changed = true;
6340                                    return null;
6341                                }
6342                            }
6343
6344                            // Yay! Either the set matched or we're looking for the last chosen
6345                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6346                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6347                            return ri;
6348                        }
6349                    }
6350                } finally {
6351                    if (changed) {
6352                        if (DEBUG_PREFERRED) {
6353                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6354                        }
6355                        scheduleWritePackageRestrictionsLocked(userId);
6356                    }
6357                }
6358            }
6359        }
6360        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6361        return null;
6362    }
6363
6364    /*
6365     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6366     */
6367    @Override
6368    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6369            int targetUserId) {
6370        mContext.enforceCallingOrSelfPermission(
6371                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6372        List<CrossProfileIntentFilter> matches =
6373                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6374        if (matches != null) {
6375            int size = matches.size();
6376            for (int i = 0; i < size; i++) {
6377                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6378            }
6379        }
6380        if (intent.hasWebURI()) {
6381            // cross-profile app linking works only towards the parent.
6382            final int callingUid = Binder.getCallingUid();
6383            final UserInfo parent = getProfileParent(sourceUserId);
6384            synchronized(mPackages) {
6385                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6386                        false /*includeInstantApps*/);
6387                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6388                        intent, resolvedType, flags, sourceUserId, parent.id);
6389                return xpDomainInfo != null;
6390            }
6391        }
6392        return false;
6393    }
6394
6395    private UserInfo getProfileParent(int userId) {
6396        final long identity = Binder.clearCallingIdentity();
6397        try {
6398            return sUserManager.getProfileParent(userId);
6399        } finally {
6400            Binder.restoreCallingIdentity(identity);
6401        }
6402    }
6403
6404    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6405            String resolvedType, int userId) {
6406        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6407        if (resolver != null) {
6408            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6409        }
6410        return null;
6411    }
6412
6413    @Override
6414    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6415            String resolvedType, int flags, int userId) {
6416        try {
6417            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6418
6419            return new ParceledListSlice<>(
6420                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6421        } finally {
6422            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6423        }
6424    }
6425
6426    /**
6427     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6428     * instant, returns {@code null}.
6429     */
6430    private String getInstantAppPackageName(int callingUid) {
6431        synchronized (mPackages) {
6432            // If the caller is an isolated app use the owner's uid for the lookup.
6433            if (Process.isIsolated(callingUid)) {
6434                callingUid = mIsolatedOwners.get(callingUid);
6435            }
6436            final int appId = UserHandle.getAppId(callingUid);
6437            final Object obj = mSettings.getUserIdLPr(appId);
6438            if (obj instanceof PackageSetting) {
6439                final PackageSetting ps = (PackageSetting) obj;
6440                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6441                return isInstantApp ? ps.pkg.packageName : null;
6442            }
6443        }
6444        return null;
6445    }
6446
6447    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6448            String resolvedType, int flags, int userId) {
6449        return queryIntentActivitiesInternal(
6450                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6451                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6452    }
6453
6454    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6455            String resolvedType, int flags, int filterCallingUid, int userId,
6456            boolean resolveForStart, boolean allowDynamicSplits) {
6457        if (!sUserManager.exists(userId)) return Collections.emptyList();
6458        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6459        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6460                false /* requireFullPermission */, false /* checkShell */,
6461                "query intent activities");
6462        final String pkgName = intent.getPackage();
6463        ComponentName comp = intent.getComponent();
6464        if (comp == null) {
6465            if (intent.getSelector() != null) {
6466                intent = intent.getSelector();
6467                comp = intent.getComponent();
6468            }
6469        }
6470
6471        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6472                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6473        if (comp != null) {
6474            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6475            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6476            if (ai != null) {
6477                // When specifying an explicit component, we prevent the activity from being
6478                // used when either 1) the calling package is normal and the activity is within
6479                // an ephemeral application or 2) the calling package is ephemeral and the
6480                // activity is not visible to ephemeral applications.
6481                final boolean matchInstantApp =
6482                        (flags & PackageManager.MATCH_INSTANT) != 0;
6483                final boolean matchVisibleToInstantAppOnly =
6484                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6485                final boolean matchExplicitlyVisibleOnly =
6486                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6487                final boolean isCallerInstantApp =
6488                        instantAppPkgName != null;
6489                final boolean isTargetSameInstantApp =
6490                        comp.getPackageName().equals(instantAppPkgName);
6491                final boolean isTargetInstantApp =
6492                        (ai.applicationInfo.privateFlags
6493                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6494                final boolean isTargetVisibleToInstantApp =
6495                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6496                final boolean isTargetExplicitlyVisibleToInstantApp =
6497                        isTargetVisibleToInstantApp
6498                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6499                final boolean isTargetHiddenFromInstantApp =
6500                        !isTargetVisibleToInstantApp
6501                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6502                final boolean blockResolution =
6503                        !isTargetSameInstantApp
6504                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6505                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6506                                        && isTargetHiddenFromInstantApp));
6507                if (!blockResolution) {
6508                    final ResolveInfo ri = new ResolveInfo();
6509                    ri.activityInfo = ai;
6510                    list.add(ri);
6511                }
6512            }
6513            return applyPostResolutionFilter(
6514                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6515        }
6516
6517        // reader
6518        boolean sortResult = false;
6519        boolean addEphemeral = false;
6520        List<ResolveInfo> result;
6521        final boolean ephemeralDisabled = isEphemeralDisabled();
6522        synchronized (mPackages) {
6523            if (pkgName == null) {
6524                List<CrossProfileIntentFilter> matchingFilters =
6525                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6526                // Check for results that need to skip the current profile.
6527                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6528                        resolvedType, flags, userId);
6529                if (xpResolveInfo != null) {
6530                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6531                    xpResult.add(xpResolveInfo);
6532                    return applyPostResolutionFilter(
6533                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6534                            allowDynamicSplits, filterCallingUid, userId);
6535                }
6536
6537                // Check for results in the current profile.
6538                result = filterIfNotSystemUser(mActivities.queryIntent(
6539                        intent, resolvedType, flags, userId), userId);
6540                addEphemeral = !ephemeralDisabled
6541                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6542                // Check for cross profile results.
6543                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6544                xpResolveInfo = queryCrossProfileIntents(
6545                        matchingFilters, intent, resolvedType, flags, userId,
6546                        hasNonNegativePriorityResult);
6547                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6548                    boolean isVisibleToUser = filterIfNotSystemUser(
6549                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6550                    if (isVisibleToUser) {
6551                        result.add(xpResolveInfo);
6552                        sortResult = true;
6553                    }
6554                }
6555                if (intent.hasWebURI()) {
6556                    CrossProfileDomainInfo xpDomainInfo = null;
6557                    final UserInfo parent = getProfileParent(userId);
6558                    if (parent != null) {
6559                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6560                                flags, userId, parent.id);
6561                    }
6562                    if (xpDomainInfo != null) {
6563                        if (xpResolveInfo != null) {
6564                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6565                            // in the result.
6566                            result.remove(xpResolveInfo);
6567                        }
6568                        if (result.size() == 0 && !addEphemeral) {
6569                            // No result in current profile, but found candidate in parent user.
6570                            // And we are not going to add emphemeral app, so we can return the
6571                            // result straight away.
6572                            result.add(xpDomainInfo.resolveInfo);
6573                            return applyPostResolutionFilter(result, instantAppPkgName,
6574                                    allowDynamicSplits, filterCallingUid, userId);
6575                        }
6576                    } else if (result.size() <= 1 && !addEphemeral) {
6577                        // No result in parent user and <= 1 result in current profile, and we
6578                        // are not going to add emphemeral app, so we can return the result without
6579                        // further processing.
6580                        return applyPostResolutionFilter(result, instantAppPkgName,
6581                                allowDynamicSplits, filterCallingUid, userId);
6582                    }
6583                    // We have more than one candidate (combining results from current and parent
6584                    // profile), so we need filtering and sorting.
6585                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6586                            intent, flags, result, xpDomainInfo, userId);
6587                    sortResult = true;
6588                }
6589            } else {
6590                final PackageParser.Package pkg = mPackages.get(pkgName);
6591                result = null;
6592                if (pkg != null) {
6593                    result = filterIfNotSystemUser(
6594                            mActivities.queryIntentForPackage(
6595                                    intent, resolvedType, flags, pkg.activities, userId),
6596                            userId);
6597                }
6598                if (result == null || result.size() == 0) {
6599                    // the caller wants to resolve for a particular package; however, there
6600                    // were no installed results, so, try to find an ephemeral result
6601                    addEphemeral = !ephemeralDisabled
6602                            && isInstantAppAllowed(
6603                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6604                    if (result == null) {
6605                        result = new ArrayList<>();
6606                    }
6607                }
6608            }
6609        }
6610        if (addEphemeral) {
6611            result = maybeAddInstantAppInstaller(
6612                    result, intent, resolvedType, flags, userId, resolveForStart);
6613        }
6614        if (sortResult) {
6615            Collections.sort(result, mResolvePrioritySorter);
6616        }
6617        return applyPostResolutionFilter(
6618                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6619    }
6620
6621    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6622            String resolvedType, int flags, int userId, boolean resolveForStart) {
6623        // first, check to see if we've got an instant app already installed
6624        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6625        ResolveInfo localInstantApp = null;
6626        boolean blockResolution = false;
6627        if (!alreadyResolvedLocally) {
6628            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6629                    flags
6630                        | PackageManager.GET_RESOLVED_FILTER
6631                        | PackageManager.MATCH_INSTANT
6632                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6633                    userId);
6634            for (int i = instantApps.size() - 1; i >= 0; --i) {
6635                final ResolveInfo info = instantApps.get(i);
6636                final String packageName = info.activityInfo.packageName;
6637                final PackageSetting ps = mSettings.mPackages.get(packageName);
6638                if (ps.getInstantApp(userId)) {
6639                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6640                    final int status = (int)(packedStatus >> 32);
6641                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6642                        // there's a local instant application installed, but, the user has
6643                        // chosen to never use it; skip resolution and don't acknowledge
6644                        // an instant application is even available
6645                        if (DEBUG_INSTANT) {
6646                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6647                        }
6648                        blockResolution = true;
6649                        break;
6650                    } else {
6651                        // we have a locally installed instant application; skip resolution
6652                        // but acknowledge there's an instant application available
6653                        if (DEBUG_INSTANT) {
6654                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6655                        }
6656                        localInstantApp = info;
6657                        break;
6658                    }
6659                }
6660            }
6661        }
6662        // no app installed, let's see if one's available
6663        AuxiliaryResolveInfo auxiliaryResponse = null;
6664        if (!blockResolution) {
6665            if (localInstantApp == null) {
6666                // we don't have an instant app locally, resolve externally
6667                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6668                final InstantAppRequest requestObject = new InstantAppRequest(
6669                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6670                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6671                        resolveForStart);
6672                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6673                        mInstantAppResolverConnection, requestObject);
6674                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6675            } else {
6676                // we have an instant application locally, but, we can't admit that since
6677                // callers shouldn't be able to determine prior browsing. create a dummy
6678                // auxiliary response so the downstream code behaves as if there's an
6679                // instant application available externally. when it comes time to start
6680                // the instant application, we'll do the right thing.
6681                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6682                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6683                                        ai.packageName, ai.versionCode, null /* splitName */);
6684            }
6685        }
6686        if (intent.isWebIntent() && auxiliaryResponse == null) {
6687            return result;
6688        }
6689        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6690        if (ps == null) {
6691            return result;
6692        }
6693        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6694        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6695                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6696        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6697                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6698        // add a non-generic filter
6699        ephemeralInstaller.filter = new IntentFilter();
6700        if (intent.getAction() != null) {
6701            ephemeralInstaller.filter.addAction(intent.getAction());
6702        }
6703        if (intent.getData() != null && intent.getData().getPath() != null) {
6704            ephemeralInstaller.filter.addDataPath(
6705                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6706        }
6707        ephemeralInstaller.isInstantAppAvailable = true;
6708        // make sure this resolver is the default
6709        ephemeralInstaller.isDefault = true;
6710        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6711        if (DEBUG_INSTANT) {
6712            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6713        }
6714
6715        result.add(ephemeralInstaller);
6716        return result;
6717    }
6718
6719    private static class CrossProfileDomainInfo {
6720        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6721        ResolveInfo resolveInfo;
6722        /* Best domain verification status of the activities found in the other profile */
6723        int bestDomainVerificationStatus;
6724    }
6725
6726    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6727            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6728        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6729                sourceUserId)) {
6730            return null;
6731        }
6732        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6733                resolvedType, flags, parentUserId);
6734
6735        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6736            return null;
6737        }
6738        CrossProfileDomainInfo result = null;
6739        int size = resultTargetUser.size();
6740        for (int i = 0; i < size; i++) {
6741            ResolveInfo riTargetUser = resultTargetUser.get(i);
6742            // Intent filter verification is only for filters that specify a host. So don't return
6743            // those that handle all web uris.
6744            if (riTargetUser.handleAllWebDataURI) {
6745                continue;
6746            }
6747            String packageName = riTargetUser.activityInfo.packageName;
6748            PackageSetting ps = mSettings.mPackages.get(packageName);
6749            if (ps == null) {
6750                continue;
6751            }
6752            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6753            int status = (int)(verificationState >> 32);
6754            if (result == null) {
6755                result = new CrossProfileDomainInfo();
6756                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6757                        sourceUserId, parentUserId);
6758                result.bestDomainVerificationStatus = status;
6759            } else {
6760                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6761                        result.bestDomainVerificationStatus);
6762            }
6763        }
6764        // Don't consider matches with status NEVER across profiles.
6765        if (result != null && result.bestDomainVerificationStatus
6766                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6767            return null;
6768        }
6769        return result;
6770    }
6771
6772    /**
6773     * Verification statuses are ordered from the worse to the best, except for
6774     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6775     */
6776    private int bestDomainVerificationStatus(int status1, int status2) {
6777        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6778            return status2;
6779        }
6780        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6781            return status1;
6782        }
6783        return (int) MathUtils.max(status1, status2);
6784    }
6785
6786    private boolean isUserEnabled(int userId) {
6787        long callingId = Binder.clearCallingIdentity();
6788        try {
6789            UserInfo userInfo = sUserManager.getUserInfo(userId);
6790            return userInfo != null && userInfo.isEnabled();
6791        } finally {
6792            Binder.restoreCallingIdentity(callingId);
6793        }
6794    }
6795
6796    /**
6797     * Filter out activities with systemUserOnly flag set, when current user is not System.
6798     *
6799     * @return filtered list
6800     */
6801    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6802        if (userId == UserHandle.USER_SYSTEM) {
6803            return resolveInfos;
6804        }
6805        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6806            ResolveInfo info = resolveInfos.get(i);
6807            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6808                resolveInfos.remove(i);
6809            }
6810        }
6811        return resolveInfos;
6812    }
6813
6814    /**
6815     * Filters out ephemeral activities.
6816     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6817     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6818     *
6819     * @param resolveInfos The pre-filtered list of resolved activities
6820     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6821     *          is performed.
6822     * @return A filtered list of resolved activities.
6823     */
6824    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6825            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6826        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6827            final ResolveInfo info = resolveInfos.get(i);
6828            // allow activities that are defined in the provided package
6829            if (allowDynamicSplits
6830                    && info.activityInfo != null
6831                    && info.activityInfo.splitName != null
6832                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6833                            info.activityInfo.splitName)) {
6834                if (mInstantAppInstallerActivity == null) {
6835                    if (DEBUG_INSTALL) {
6836                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6837                    }
6838                    resolveInfos.remove(i);
6839                    continue;
6840                }
6841                // requested activity is defined in a split that hasn't been installed yet.
6842                // add the installer to the resolve list
6843                if (DEBUG_INSTALL) {
6844                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6845                }
6846                final ResolveInfo installerInfo = new ResolveInfo(
6847                        mInstantAppInstallerInfo);
6848                final ComponentName installFailureActivity = findInstallFailureActivity(
6849                        info.activityInfo.packageName,  filterCallingUid, userId);
6850                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6851                        installFailureActivity,
6852                        info.activityInfo.packageName,
6853                        info.activityInfo.applicationInfo.versionCode,
6854                        info.activityInfo.splitName);
6855                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6856                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6857                // add a non-generic filter
6858                installerInfo.filter = new IntentFilter();
6859
6860                // This resolve info may appear in the chooser UI, so let us make it
6861                // look as the one it replaces as far as the user is concerned which
6862                // requires loading the correct label and icon for the resolve info.
6863                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6864                installerInfo.labelRes = info.resolveLabelResId();
6865                installerInfo.icon = info.resolveIconResId();
6866
6867                // propagate priority/preferred order/default
6868                installerInfo.priority = info.priority;
6869                installerInfo.preferredOrder = info.preferredOrder;
6870                installerInfo.isDefault = info.isDefault;
6871                installerInfo.isInstantAppAvailable = true;
6872                resolveInfos.set(i, installerInfo);
6873                continue;
6874            }
6875            // caller is a full app, don't need to apply any other filtering
6876            if (ephemeralPkgName == null) {
6877                continue;
6878            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6879                // caller is same app; don't need to apply any other filtering
6880                continue;
6881            }
6882            // allow activities that have been explicitly exposed to ephemeral apps
6883            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6884            if (!isEphemeralApp
6885                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6886                continue;
6887            }
6888            resolveInfos.remove(i);
6889        }
6890        return resolveInfos;
6891    }
6892
6893    /**
6894     * Returns the activity component that can handle install failures.
6895     * <p>By default, the instant application installer handles failures. However, an
6896     * application may want to handle failures on its own. Applications do this by
6897     * creating an activity with an intent filter that handles the action
6898     * {@link Intent#ACTION_INSTALL_FAILURE}.
6899     */
6900    private @Nullable ComponentName findInstallFailureActivity(
6901            String packageName, int filterCallingUid, int userId) {
6902        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6903        failureActivityIntent.setPackage(packageName);
6904        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6905        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6906                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6907                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6908        final int NR = result.size();
6909        if (NR > 0) {
6910            for (int i = 0; i < NR; i++) {
6911                final ResolveInfo info = result.get(i);
6912                if (info.activityInfo.splitName != null) {
6913                    continue;
6914                }
6915                return new ComponentName(packageName, info.activityInfo.name);
6916            }
6917        }
6918        return null;
6919    }
6920
6921    /**
6922     * @param resolveInfos list of resolve infos in descending priority order
6923     * @return if the list contains a resolve info with non-negative priority
6924     */
6925    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6926        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6927    }
6928
6929    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6930            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6931            int userId) {
6932        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6933
6934        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6935            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6936                    candidates.size());
6937        }
6938
6939        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6940        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6941        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6942        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6943        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6944        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6945
6946        synchronized (mPackages) {
6947            final int count = candidates.size();
6948            // First, try to use linked apps. Partition the candidates into four lists:
6949            // one for the final results, one for the "do not use ever", one for "undefined status"
6950            // and finally one for "browser app type".
6951            for (int n=0; n<count; n++) {
6952                ResolveInfo info = candidates.get(n);
6953                String packageName = info.activityInfo.packageName;
6954                PackageSetting ps = mSettings.mPackages.get(packageName);
6955                if (ps != null) {
6956                    // Add to the special match all list (Browser use case)
6957                    if (info.handleAllWebDataURI) {
6958                        matchAllList.add(info);
6959                        continue;
6960                    }
6961                    // Try to get the status from User settings first
6962                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6963                    int status = (int)(packedStatus >> 32);
6964                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6965                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6966                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6967                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6968                                    + " : linkgen=" + linkGeneration);
6969                        }
6970                        // Use link-enabled generation as preferredOrder, i.e.
6971                        // prefer newly-enabled over earlier-enabled.
6972                        info.preferredOrder = linkGeneration;
6973                        alwaysList.add(info);
6974                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6975                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6976                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6977                        }
6978                        neverList.add(info);
6979                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6980                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6981                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6982                        }
6983                        alwaysAskList.add(info);
6984                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6985                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6986                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6987                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6988                        }
6989                        undefinedList.add(info);
6990                    }
6991                }
6992            }
6993
6994            // We'll want to include browser possibilities in a few cases
6995            boolean includeBrowser = false;
6996
6997            // First try to add the "always" resolution(s) for the current user, if any
6998            if (alwaysList.size() > 0) {
6999                result.addAll(alwaysList);
7000            } else {
7001                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7002                result.addAll(undefinedList);
7003                // Maybe add one for the other profile.
7004                if (xpDomainInfo != null && (
7005                        xpDomainInfo.bestDomainVerificationStatus
7006                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7007                    result.add(xpDomainInfo.resolveInfo);
7008                }
7009                includeBrowser = true;
7010            }
7011
7012            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7013            // If there were 'always' entries their preferred order has been set, so we also
7014            // back that off to make the alternatives equivalent
7015            if (alwaysAskList.size() > 0) {
7016                for (ResolveInfo i : result) {
7017                    i.preferredOrder = 0;
7018                }
7019                result.addAll(alwaysAskList);
7020                includeBrowser = true;
7021            }
7022
7023            if (includeBrowser) {
7024                // Also add browsers (all of them or only the default one)
7025                if (DEBUG_DOMAIN_VERIFICATION) {
7026                    Slog.v(TAG, "   ...including browsers in candidate set");
7027                }
7028                if ((matchFlags & MATCH_ALL) != 0) {
7029                    result.addAll(matchAllList);
7030                } else {
7031                    // Browser/generic handling case.  If there's a default browser, go straight
7032                    // to that (but only if there is no other higher-priority match).
7033                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7034                    int maxMatchPrio = 0;
7035                    ResolveInfo defaultBrowserMatch = null;
7036                    final int numCandidates = matchAllList.size();
7037                    for (int n = 0; n < numCandidates; n++) {
7038                        ResolveInfo info = matchAllList.get(n);
7039                        // track the highest overall match priority...
7040                        if (info.priority > maxMatchPrio) {
7041                            maxMatchPrio = info.priority;
7042                        }
7043                        // ...and the highest-priority default browser match
7044                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7045                            if (defaultBrowserMatch == null
7046                                    || (defaultBrowserMatch.priority < info.priority)) {
7047                                if (debug) {
7048                                    Slog.v(TAG, "Considering default browser match " + info);
7049                                }
7050                                defaultBrowserMatch = info;
7051                            }
7052                        }
7053                    }
7054                    if (defaultBrowserMatch != null
7055                            && defaultBrowserMatch.priority >= maxMatchPrio
7056                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7057                    {
7058                        if (debug) {
7059                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7060                        }
7061                        result.add(defaultBrowserMatch);
7062                    } else {
7063                        result.addAll(matchAllList);
7064                    }
7065                }
7066
7067                // If there is nothing selected, add all candidates and remove the ones that the user
7068                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7069                if (result.size() == 0) {
7070                    result.addAll(candidates);
7071                    result.removeAll(neverList);
7072                }
7073            }
7074        }
7075        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7076            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7077                    result.size());
7078            for (ResolveInfo info : result) {
7079                Slog.v(TAG, "  + " + info.activityInfo);
7080            }
7081        }
7082        return result;
7083    }
7084
7085    // Returns a packed value as a long:
7086    //
7087    // high 'int'-sized word: link status: undefined/ask/never/always.
7088    // low 'int'-sized word: relative priority among 'always' results.
7089    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7090        long result = ps.getDomainVerificationStatusForUser(userId);
7091        // if none available, get the master status
7092        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7093            if (ps.getIntentFilterVerificationInfo() != null) {
7094                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7095            }
7096        }
7097        return result;
7098    }
7099
7100    private ResolveInfo querySkipCurrentProfileIntents(
7101            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7102            int flags, int sourceUserId) {
7103        if (matchingFilters != null) {
7104            int size = matchingFilters.size();
7105            for (int i = 0; i < size; i ++) {
7106                CrossProfileIntentFilter filter = matchingFilters.get(i);
7107                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7108                    // Checking if there are activities in the target user that can handle the
7109                    // intent.
7110                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7111                            resolvedType, flags, sourceUserId);
7112                    if (resolveInfo != null) {
7113                        return resolveInfo;
7114                    }
7115                }
7116            }
7117        }
7118        return null;
7119    }
7120
7121    // Return matching ResolveInfo in target user if any.
7122    private ResolveInfo queryCrossProfileIntents(
7123            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7124            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7125        if (matchingFilters != null) {
7126            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7127            // match the same intent. For performance reasons, it is better not to
7128            // run queryIntent twice for the same userId
7129            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7130            int size = matchingFilters.size();
7131            for (int i = 0; i < size; i++) {
7132                CrossProfileIntentFilter filter = matchingFilters.get(i);
7133                int targetUserId = filter.getTargetUserId();
7134                boolean skipCurrentProfile =
7135                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7136                boolean skipCurrentProfileIfNoMatchFound =
7137                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7138                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7139                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7140                    // Checking if there are activities in the target user that can handle the
7141                    // intent.
7142                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7143                            resolvedType, flags, sourceUserId);
7144                    if (resolveInfo != null) return resolveInfo;
7145                    alreadyTriedUserIds.put(targetUserId, true);
7146                }
7147            }
7148        }
7149        return null;
7150    }
7151
7152    /**
7153     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7154     * will forward the intent to the filter's target user.
7155     * Otherwise, returns null.
7156     */
7157    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7158            String resolvedType, int flags, int sourceUserId) {
7159        int targetUserId = filter.getTargetUserId();
7160        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7161                resolvedType, flags, targetUserId);
7162        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7163            // If all the matches in the target profile are suspended, return null.
7164            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7165                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7166                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7167                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7168                            targetUserId);
7169                }
7170            }
7171        }
7172        return null;
7173    }
7174
7175    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7176            int sourceUserId, int targetUserId) {
7177        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7178        long ident = Binder.clearCallingIdentity();
7179        boolean targetIsProfile;
7180        try {
7181            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7182        } finally {
7183            Binder.restoreCallingIdentity(ident);
7184        }
7185        String className;
7186        if (targetIsProfile) {
7187            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7188        } else {
7189            className = FORWARD_INTENT_TO_PARENT;
7190        }
7191        ComponentName forwardingActivityComponentName = new ComponentName(
7192                mAndroidApplication.packageName, className);
7193        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7194                sourceUserId);
7195        if (!targetIsProfile) {
7196            forwardingActivityInfo.showUserIcon = targetUserId;
7197            forwardingResolveInfo.noResourceId = true;
7198        }
7199        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7200        forwardingResolveInfo.priority = 0;
7201        forwardingResolveInfo.preferredOrder = 0;
7202        forwardingResolveInfo.match = 0;
7203        forwardingResolveInfo.isDefault = true;
7204        forwardingResolveInfo.filter = filter;
7205        forwardingResolveInfo.targetUserId = targetUserId;
7206        return forwardingResolveInfo;
7207    }
7208
7209    @Override
7210    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7211            Intent[] specifics, String[] specificTypes, Intent intent,
7212            String resolvedType, int flags, int userId) {
7213        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7214                specificTypes, intent, resolvedType, flags, userId));
7215    }
7216
7217    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7218            Intent[] specifics, String[] specificTypes, Intent intent,
7219            String resolvedType, int flags, int userId) {
7220        if (!sUserManager.exists(userId)) return Collections.emptyList();
7221        final int callingUid = Binder.getCallingUid();
7222        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7223                false /*includeInstantApps*/);
7224        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7225                false /*requireFullPermission*/, false /*checkShell*/,
7226                "query intent activity options");
7227        final String resultsAction = intent.getAction();
7228
7229        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7230                | PackageManager.GET_RESOLVED_FILTER, userId);
7231
7232        if (DEBUG_INTENT_MATCHING) {
7233            Log.v(TAG, "Query " + intent + ": " + results);
7234        }
7235
7236        int specificsPos = 0;
7237        int N;
7238
7239        // todo: note that the algorithm used here is O(N^2).  This
7240        // isn't a problem in our current environment, but if we start running
7241        // into situations where we have more than 5 or 10 matches then this
7242        // should probably be changed to something smarter...
7243
7244        // First we go through and resolve each of the specific items
7245        // that were supplied, taking care of removing any corresponding
7246        // duplicate items in the generic resolve list.
7247        if (specifics != null) {
7248            for (int i=0; i<specifics.length; i++) {
7249                final Intent sintent = specifics[i];
7250                if (sintent == null) {
7251                    continue;
7252                }
7253
7254                if (DEBUG_INTENT_MATCHING) {
7255                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7256                }
7257
7258                String action = sintent.getAction();
7259                if (resultsAction != null && resultsAction.equals(action)) {
7260                    // If this action was explicitly requested, then don't
7261                    // remove things that have it.
7262                    action = null;
7263                }
7264
7265                ResolveInfo ri = null;
7266                ActivityInfo ai = null;
7267
7268                ComponentName comp = sintent.getComponent();
7269                if (comp == null) {
7270                    ri = resolveIntent(
7271                        sintent,
7272                        specificTypes != null ? specificTypes[i] : null,
7273                            flags, userId);
7274                    if (ri == null) {
7275                        continue;
7276                    }
7277                    if (ri == mResolveInfo) {
7278                        // ACK!  Must do something better with this.
7279                    }
7280                    ai = ri.activityInfo;
7281                    comp = new ComponentName(ai.applicationInfo.packageName,
7282                            ai.name);
7283                } else {
7284                    ai = getActivityInfo(comp, flags, userId);
7285                    if (ai == null) {
7286                        continue;
7287                    }
7288                }
7289
7290                // Look for any generic query activities that are duplicates
7291                // of this specific one, and remove them from the results.
7292                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7293                N = results.size();
7294                int j;
7295                for (j=specificsPos; j<N; j++) {
7296                    ResolveInfo sri = results.get(j);
7297                    if ((sri.activityInfo.name.equals(comp.getClassName())
7298                            && sri.activityInfo.applicationInfo.packageName.equals(
7299                                    comp.getPackageName()))
7300                        || (action != null && sri.filter.matchAction(action))) {
7301                        results.remove(j);
7302                        if (DEBUG_INTENT_MATCHING) Log.v(
7303                            TAG, "Removing duplicate item from " + j
7304                            + " due to specific " + specificsPos);
7305                        if (ri == null) {
7306                            ri = sri;
7307                        }
7308                        j--;
7309                        N--;
7310                    }
7311                }
7312
7313                // Add this specific item to its proper place.
7314                if (ri == null) {
7315                    ri = new ResolveInfo();
7316                    ri.activityInfo = ai;
7317                }
7318                results.add(specificsPos, ri);
7319                ri.specificIndex = i;
7320                specificsPos++;
7321            }
7322        }
7323
7324        // Now we go through the remaining generic results and remove any
7325        // duplicate actions that are found here.
7326        N = results.size();
7327        for (int i=specificsPos; i<N-1; i++) {
7328            final ResolveInfo rii = results.get(i);
7329            if (rii.filter == null) {
7330                continue;
7331            }
7332
7333            // Iterate over all of the actions of this result's intent
7334            // filter...  typically this should be just one.
7335            final Iterator<String> it = rii.filter.actionsIterator();
7336            if (it == null) {
7337                continue;
7338            }
7339            while (it.hasNext()) {
7340                final String action = it.next();
7341                if (resultsAction != null && resultsAction.equals(action)) {
7342                    // If this action was explicitly requested, then don't
7343                    // remove things that have it.
7344                    continue;
7345                }
7346                for (int j=i+1; j<N; j++) {
7347                    final ResolveInfo rij = results.get(j);
7348                    if (rij.filter != null && rij.filter.hasAction(action)) {
7349                        results.remove(j);
7350                        if (DEBUG_INTENT_MATCHING) Log.v(
7351                            TAG, "Removing duplicate item from " + j
7352                            + " due to action " + action + " at " + i);
7353                        j--;
7354                        N--;
7355                    }
7356                }
7357            }
7358
7359            // If the caller didn't request filter information, drop it now
7360            // so we don't have to marshall/unmarshall it.
7361            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7362                rii.filter = null;
7363            }
7364        }
7365
7366        // Filter out the caller activity if so requested.
7367        if (caller != null) {
7368            N = results.size();
7369            for (int i=0; i<N; i++) {
7370                ActivityInfo ainfo = results.get(i).activityInfo;
7371                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7372                        && caller.getClassName().equals(ainfo.name)) {
7373                    results.remove(i);
7374                    break;
7375                }
7376            }
7377        }
7378
7379        // If the caller didn't request filter information,
7380        // drop them now so we don't have to
7381        // marshall/unmarshall it.
7382        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7383            N = results.size();
7384            for (int i=0; i<N; i++) {
7385                results.get(i).filter = null;
7386            }
7387        }
7388
7389        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7390        return results;
7391    }
7392
7393    @Override
7394    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7395            String resolvedType, int flags, int userId) {
7396        return new ParceledListSlice<>(
7397                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7398                        false /*allowDynamicSplits*/));
7399    }
7400
7401    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7402            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7403        if (!sUserManager.exists(userId)) return Collections.emptyList();
7404        final int callingUid = Binder.getCallingUid();
7405        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7406                false /*requireFullPermission*/, false /*checkShell*/,
7407                "query intent receivers");
7408        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7409        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7410                false /*includeInstantApps*/);
7411        ComponentName comp = intent.getComponent();
7412        if (comp == null) {
7413            if (intent.getSelector() != null) {
7414                intent = intent.getSelector();
7415                comp = intent.getComponent();
7416            }
7417        }
7418        if (comp != null) {
7419            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7420            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7421            if (ai != null) {
7422                // When specifying an explicit component, we prevent the activity from being
7423                // used when either 1) the calling package is normal and the activity is within
7424                // an instant application or 2) the calling package is ephemeral and the
7425                // activity is not visible to instant applications.
7426                final boolean matchInstantApp =
7427                        (flags & PackageManager.MATCH_INSTANT) != 0;
7428                final boolean matchVisibleToInstantAppOnly =
7429                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7430                final boolean matchExplicitlyVisibleOnly =
7431                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7432                final boolean isCallerInstantApp =
7433                        instantAppPkgName != null;
7434                final boolean isTargetSameInstantApp =
7435                        comp.getPackageName().equals(instantAppPkgName);
7436                final boolean isTargetInstantApp =
7437                        (ai.applicationInfo.privateFlags
7438                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7439                final boolean isTargetVisibleToInstantApp =
7440                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7441                final boolean isTargetExplicitlyVisibleToInstantApp =
7442                        isTargetVisibleToInstantApp
7443                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7444                final boolean isTargetHiddenFromInstantApp =
7445                        !isTargetVisibleToInstantApp
7446                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7447                final boolean blockResolution =
7448                        !isTargetSameInstantApp
7449                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7450                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7451                                        && isTargetHiddenFromInstantApp));
7452                if (!blockResolution) {
7453                    ResolveInfo ri = new ResolveInfo();
7454                    ri.activityInfo = ai;
7455                    list.add(ri);
7456                }
7457            }
7458            return applyPostResolutionFilter(
7459                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7460        }
7461
7462        // reader
7463        synchronized (mPackages) {
7464            String pkgName = intent.getPackage();
7465            if (pkgName == null) {
7466                final List<ResolveInfo> result =
7467                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7468                return applyPostResolutionFilter(
7469                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7470            }
7471            final PackageParser.Package pkg = mPackages.get(pkgName);
7472            if (pkg != null) {
7473                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7474                        intent, resolvedType, flags, pkg.receivers, userId);
7475                return applyPostResolutionFilter(
7476                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7477            }
7478            return Collections.emptyList();
7479        }
7480    }
7481
7482    @Override
7483    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7484        final int callingUid = Binder.getCallingUid();
7485        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7486    }
7487
7488    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7489            int userId, int callingUid) {
7490        if (!sUserManager.exists(userId)) return null;
7491        flags = updateFlagsForResolve(
7492                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7493        List<ResolveInfo> query = queryIntentServicesInternal(
7494                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7495        if (query != null) {
7496            if (query.size() >= 1) {
7497                // If there is more than one service with the same priority,
7498                // just arbitrarily pick the first one.
7499                return query.get(0);
7500            }
7501        }
7502        return null;
7503    }
7504
7505    @Override
7506    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7507            String resolvedType, int flags, int userId) {
7508        final int callingUid = Binder.getCallingUid();
7509        return new ParceledListSlice<>(queryIntentServicesInternal(
7510                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7511    }
7512
7513    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7514            String resolvedType, int flags, int userId, int callingUid,
7515            boolean includeInstantApps) {
7516        if (!sUserManager.exists(userId)) return Collections.emptyList();
7517        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7518                false /*requireFullPermission*/, false /*checkShell*/,
7519                "query intent receivers");
7520        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7521        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7522        ComponentName comp = intent.getComponent();
7523        if (comp == null) {
7524            if (intent.getSelector() != null) {
7525                intent = intent.getSelector();
7526                comp = intent.getComponent();
7527            }
7528        }
7529        if (comp != null) {
7530            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7531            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7532            if (si != null) {
7533                // When specifying an explicit component, we prevent the service from being
7534                // used when either 1) the service is in an instant application and the
7535                // caller is not the same instant application or 2) the calling package is
7536                // ephemeral and the activity is not visible to ephemeral applications.
7537                final boolean matchInstantApp =
7538                        (flags & PackageManager.MATCH_INSTANT) != 0;
7539                final boolean matchVisibleToInstantAppOnly =
7540                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7541                final boolean isCallerInstantApp =
7542                        instantAppPkgName != null;
7543                final boolean isTargetSameInstantApp =
7544                        comp.getPackageName().equals(instantAppPkgName);
7545                final boolean isTargetInstantApp =
7546                        (si.applicationInfo.privateFlags
7547                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7548                final boolean isTargetHiddenFromInstantApp =
7549                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7550                final boolean blockResolution =
7551                        !isTargetSameInstantApp
7552                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7553                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7554                                        && isTargetHiddenFromInstantApp));
7555                if (!blockResolution) {
7556                    final ResolveInfo ri = new ResolveInfo();
7557                    ri.serviceInfo = si;
7558                    list.add(ri);
7559                }
7560            }
7561            return list;
7562        }
7563
7564        // reader
7565        synchronized (mPackages) {
7566            String pkgName = intent.getPackage();
7567            if (pkgName == null) {
7568                return applyPostServiceResolutionFilter(
7569                        mServices.queryIntent(intent, resolvedType, flags, userId),
7570                        instantAppPkgName);
7571            }
7572            final PackageParser.Package pkg = mPackages.get(pkgName);
7573            if (pkg != null) {
7574                return applyPostServiceResolutionFilter(
7575                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7576                                userId),
7577                        instantAppPkgName);
7578            }
7579            return Collections.emptyList();
7580        }
7581    }
7582
7583    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7584            String instantAppPkgName) {
7585        if (instantAppPkgName == null) {
7586            return resolveInfos;
7587        }
7588        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7589            final ResolveInfo info = resolveInfos.get(i);
7590            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7591            // allow services that are defined in the provided package
7592            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7593                if (info.serviceInfo.splitName != null
7594                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7595                                info.serviceInfo.splitName)) {
7596                    // requested service is defined in a split that hasn't been installed yet.
7597                    // add the installer to the resolve list
7598                    if (DEBUG_INSTANT) {
7599                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7600                    }
7601                    final ResolveInfo installerInfo = new ResolveInfo(
7602                            mInstantAppInstallerInfo);
7603                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7604                            null /* installFailureActivity */,
7605                            info.serviceInfo.packageName,
7606                            info.serviceInfo.applicationInfo.versionCode,
7607                            info.serviceInfo.splitName);
7608                    // make sure this resolver is the default
7609                    installerInfo.isDefault = true;
7610                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7611                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7612                    // add a non-generic filter
7613                    installerInfo.filter = new IntentFilter();
7614                    // load resources from the correct package
7615                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7616                    resolveInfos.set(i, installerInfo);
7617                }
7618                continue;
7619            }
7620            // allow services that have been explicitly exposed to ephemeral apps
7621            if (!isEphemeralApp
7622                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7623                continue;
7624            }
7625            resolveInfos.remove(i);
7626        }
7627        return resolveInfos;
7628    }
7629
7630    @Override
7631    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7632            String resolvedType, int flags, int userId) {
7633        return new ParceledListSlice<>(
7634                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7635    }
7636
7637    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7638            Intent intent, String resolvedType, int flags, int userId) {
7639        if (!sUserManager.exists(userId)) return Collections.emptyList();
7640        final int callingUid = Binder.getCallingUid();
7641        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7642        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7643                false /*includeInstantApps*/);
7644        ComponentName comp = intent.getComponent();
7645        if (comp == null) {
7646            if (intent.getSelector() != null) {
7647                intent = intent.getSelector();
7648                comp = intent.getComponent();
7649            }
7650        }
7651        if (comp != null) {
7652            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7653            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7654            if (pi != null) {
7655                // When specifying an explicit component, we prevent the provider from being
7656                // used when either 1) the provider is in an instant application and the
7657                // caller is not the same instant application or 2) the calling package is an
7658                // instant application and the provider is not visible to instant applications.
7659                final boolean matchInstantApp =
7660                        (flags & PackageManager.MATCH_INSTANT) != 0;
7661                final boolean matchVisibleToInstantAppOnly =
7662                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7663                final boolean isCallerInstantApp =
7664                        instantAppPkgName != null;
7665                final boolean isTargetSameInstantApp =
7666                        comp.getPackageName().equals(instantAppPkgName);
7667                final boolean isTargetInstantApp =
7668                        (pi.applicationInfo.privateFlags
7669                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7670                final boolean isTargetHiddenFromInstantApp =
7671                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7672                final boolean blockResolution =
7673                        !isTargetSameInstantApp
7674                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7675                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7676                                        && isTargetHiddenFromInstantApp));
7677                if (!blockResolution) {
7678                    final ResolveInfo ri = new ResolveInfo();
7679                    ri.providerInfo = pi;
7680                    list.add(ri);
7681                }
7682            }
7683            return list;
7684        }
7685
7686        // reader
7687        synchronized (mPackages) {
7688            String pkgName = intent.getPackage();
7689            if (pkgName == null) {
7690                return applyPostContentProviderResolutionFilter(
7691                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7692                        instantAppPkgName);
7693            }
7694            final PackageParser.Package pkg = mPackages.get(pkgName);
7695            if (pkg != null) {
7696                return applyPostContentProviderResolutionFilter(
7697                        mProviders.queryIntentForPackage(
7698                        intent, resolvedType, flags, pkg.providers, userId),
7699                        instantAppPkgName);
7700            }
7701            return Collections.emptyList();
7702        }
7703    }
7704
7705    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7706            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7707        if (instantAppPkgName == null) {
7708            return resolveInfos;
7709        }
7710        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7711            final ResolveInfo info = resolveInfos.get(i);
7712            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7713            // allow providers that are defined in the provided package
7714            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7715                if (info.providerInfo.splitName != null
7716                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7717                                info.providerInfo.splitName)) {
7718                    // requested provider is defined in a split that hasn't been installed yet.
7719                    // add the installer to the resolve list
7720                    if (DEBUG_INSTANT) {
7721                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7722                    }
7723                    final ResolveInfo installerInfo = new ResolveInfo(
7724                            mInstantAppInstallerInfo);
7725                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7726                            null /*failureActivity*/,
7727                            info.providerInfo.packageName,
7728                            info.providerInfo.applicationInfo.versionCode,
7729                            info.providerInfo.splitName);
7730                    // make sure this resolver is the default
7731                    installerInfo.isDefault = true;
7732                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7733                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7734                    // add a non-generic filter
7735                    installerInfo.filter = new IntentFilter();
7736                    // load resources from the correct package
7737                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7738                    resolveInfos.set(i, installerInfo);
7739                }
7740                continue;
7741            }
7742            // allow providers that have been explicitly exposed to instant applications
7743            if (!isEphemeralApp
7744                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7745                continue;
7746            }
7747            resolveInfos.remove(i);
7748        }
7749        return resolveInfos;
7750    }
7751
7752    @Override
7753    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7754        final int callingUid = Binder.getCallingUid();
7755        if (getInstantAppPackageName(callingUid) != null) {
7756            return ParceledListSlice.emptyList();
7757        }
7758        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7759        flags = updateFlagsForPackage(flags, userId, null);
7760        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7761        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7762                true /* requireFullPermission */, false /* checkShell */,
7763                "get installed packages");
7764
7765        // writer
7766        synchronized (mPackages) {
7767            ArrayList<PackageInfo> list;
7768            if (listUninstalled) {
7769                list = new ArrayList<>(mSettings.mPackages.size());
7770                for (PackageSetting ps : mSettings.mPackages.values()) {
7771                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7772                        continue;
7773                    }
7774                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7775                        continue;
7776                    }
7777                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7778                    if (pi != null) {
7779                        list.add(pi);
7780                    }
7781                }
7782            } else {
7783                list = new ArrayList<>(mPackages.size());
7784                for (PackageParser.Package p : mPackages.values()) {
7785                    final PackageSetting ps = (PackageSetting) p.mExtras;
7786                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7787                        continue;
7788                    }
7789                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7790                        continue;
7791                    }
7792                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7793                            p.mExtras, flags, userId);
7794                    if (pi != null) {
7795                        list.add(pi);
7796                    }
7797                }
7798            }
7799
7800            return new ParceledListSlice<>(list);
7801        }
7802    }
7803
7804    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7805            String[] permissions, boolean[] tmp, int flags, int userId) {
7806        int numMatch = 0;
7807        final PermissionsState permissionsState = ps.getPermissionsState();
7808        for (int i=0; i<permissions.length; i++) {
7809            final String permission = permissions[i];
7810            if (permissionsState.hasPermission(permission, userId)) {
7811                tmp[i] = true;
7812                numMatch++;
7813            } else {
7814                tmp[i] = false;
7815            }
7816        }
7817        if (numMatch == 0) {
7818            return;
7819        }
7820        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7821
7822        // The above might return null in cases of uninstalled apps or install-state
7823        // skew across users/profiles.
7824        if (pi != null) {
7825            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7826                if (numMatch == permissions.length) {
7827                    pi.requestedPermissions = permissions;
7828                } else {
7829                    pi.requestedPermissions = new String[numMatch];
7830                    numMatch = 0;
7831                    for (int i=0; i<permissions.length; i++) {
7832                        if (tmp[i]) {
7833                            pi.requestedPermissions[numMatch] = permissions[i];
7834                            numMatch++;
7835                        }
7836                    }
7837                }
7838            }
7839            list.add(pi);
7840        }
7841    }
7842
7843    @Override
7844    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7845            String[] permissions, int flags, int userId) {
7846        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7847        flags = updateFlagsForPackage(flags, userId, permissions);
7848        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7849                true /* requireFullPermission */, false /* checkShell */,
7850                "get packages holding permissions");
7851        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7852
7853        // writer
7854        synchronized (mPackages) {
7855            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7856            boolean[] tmpBools = new boolean[permissions.length];
7857            if (listUninstalled) {
7858                for (PackageSetting ps : mSettings.mPackages.values()) {
7859                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7860                            userId);
7861                }
7862            } else {
7863                for (PackageParser.Package pkg : mPackages.values()) {
7864                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7865                    if (ps != null) {
7866                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7867                                userId);
7868                    }
7869                }
7870            }
7871
7872            return new ParceledListSlice<PackageInfo>(list);
7873        }
7874    }
7875
7876    @Override
7877    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7878        final int callingUid = Binder.getCallingUid();
7879        if (getInstantAppPackageName(callingUid) != null) {
7880            return ParceledListSlice.emptyList();
7881        }
7882        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7883        flags = updateFlagsForApplication(flags, userId, null);
7884        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7885
7886        // writer
7887        synchronized (mPackages) {
7888            ArrayList<ApplicationInfo> list;
7889            if (listUninstalled) {
7890                list = new ArrayList<>(mSettings.mPackages.size());
7891                for (PackageSetting ps : mSettings.mPackages.values()) {
7892                    ApplicationInfo ai;
7893                    int effectiveFlags = flags;
7894                    if (ps.isSystem()) {
7895                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7896                    }
7897                    if (ps.pkg != null) {
7898                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7899                            continue;
7900                        }
7901                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7902                            continue;
7903                        }
7904                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7905                                ps.readUserState(userId), userId);
7906                        if (ai != null) {
7907                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7908                        }
7909                    } else {
7910                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7911                        // and already converts to externally visible package name
7912                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7913                                callingUid, effectiveFlags, userId);
7914                    }
7915                    if (ai != null) {
7916                        list.add(ai);
7917                    }
7918                }
7919            } else {
7920                list = new ArrayList<>(mPackages.size());
7921                for (PackageParser.Package p : mPackages.values()) {
7922                    if (p.mExtras != null) {
7923                        PackageSetting ps = (PackageSetting) p.mExtras;
7924                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7925                            continue;
7926                        }
7927                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7928                            continue;
7929                        }
7930                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7931                                ps.readUserState(userId), userId);
7932                        if (ai != null) {
7933                            ai.packageName = resolveExternalPackageNameLPr(p);
7934                            list.add(ai);
7935                        }
7936                    }
7937                }
7938            }
7939
7940            return new ParceledListSlice<>(list);
7941        }
7942    }
7943
7944    @Override
7945    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7946        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7947            return null;
7948        }
7949        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7950            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7951                    "getEphemeralApplications");
7952        }
7953        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7954                true /* requireFullPermission */, false /* checkShell */,
7955                "getEphemeralApplications");
7956        synchronized (mPackages) {
7957            List<InstantAppInfo> instantApps = mInstantAppRegistry
7958                    .getInstantAppsLPr(userId);
7959            if (instantApps != null) {
7960                return new ParceledListSlice<>(instantApps);
7961            }
7962        }
7963        return null;
7964    }
7965
7966    @Override
7967    public boolean isInstantApp(String packageName, int userId) {
7968        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7969                true /* requireFullPermission */, false /* checkShell */,
7970                "isInstantApp");
7971        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7972            return false;
7973        }
7974
7975        synchronized (mPackages) {
7976            int callingUid = Binder.getCallingUid();
7977            if (Process.isIsolated(callingUid)) {
7978                callingUid = mIsolatedOwners.get(callingUid);
7979            }
7980            final PackageSetting ps = mSettings.mPackages.get(packageName);
7981            PackageParser.Package pkg = mPackages.get(packageName);
7982            final boolean returnAllowed =
7983                    ps != null
7984                    && (isCallerSameApp(packageName, callingUid)
7985                            || canViewInstantApps(callingUid, userId)
7986                            || mInstantAppRegistry.isInstantAccessGranted(
7987                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7988            if (returnAllowed) {
7989                return ps.getInstantApp(userId);
7990            }
7991        }
7992        return false;
7993    }
7994
7995    @Override
7996    public byte[] getInstantAppCookie(String packageName, int userId) {
7997        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7998            return null;
7999        }
8000
8001        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8002                true /* requireFullPermission */, false /* checkShell */,
8003                "getInstantAppCookie");
8004        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8005            return null;
8006        }
8007        synchronized (mPackages) {
8008            return mInstantAppRegistry.getInstantAppCookieLPw(
8009                    packageName, userId);
8010        }
8011    }
8012
8013    @Override
8014    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8015        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8016            return true;
8017        }
8018
8019        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8020                true /* requireFullPermission */, true /* checkShell */,
8021                "setInstantAppCookie");
8022        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8023            return false;
8024        }
8025        synchronized (mPackages) {
8026            return mInstantAppRegistry.setInstantAppCookieLPw(
8027                    packageName, cookie, userId);
8028        }
8029    }
8030
8031    @Override
8032    public Bitmap getInstantAppIcon(String packageName, int userId) {
8033        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8034            return null;
8035        }
8036
8037        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8038            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8039                    "getInstantAppIcon");
8040        }
8041        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8042                true /* requireFullPermission */, false /* checkShell */,
8043                "getInstantAppIcon");
8044
8045        synchronized (mPackages) {
8046            return mInstantAppRegistry.getInstantAppIconLPw(
8047                    packageName, userId);
8048        }
8049    }
8050
8051    private boolean isCallerSameApp(String packageName, int uid) {
8052        PackageParser.Package pkg = mPackages.get(packageName);
8053        return pkg != null
8054                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8055    }
8056
8057    @Override
8058    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8059        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8060            return ParceledListSlice.emptyList();
8061        }
8062        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8063    }
8064
8065    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8066        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8067
8068        // reader
8069        synchronized (mPackages) {
8070            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8071            final int userId = UserHandle.getCallingUserId();
8072            while (i.hasNext()) {
8073                final PackageParser.Package p = i.next();
8074                if (p.applicationInfo == null) continue;
8075
8076                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8077                        && !p.applicationInfo.isDirectBootAware();
8078                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8079                        && p.applicationInfo.isDirectBootAware();
8080
8081                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8082                        && (!mSafeMode || isSystemApp(p))
8083                        && (matchesUnaware || matchesAware)) {
8084                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8085                    if (ps != null) {
8086                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8087                                ps.readUserState(userId), userId);
8088                        if (ai != null) {
8089                            finalList.add(ai);
8090                        }
8091                    }
8092                }
8093            }
8094        }
8095
8096        return finalList;
8097    }
8098
8099    @Override
8100    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8101        return resolveContentProviderInternal(name, flags, userId);
8102    }
8103
8104    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8105        if (!sUserManager.exists(userId)) return null;
8106        flags = updateFlagsForComponent(flags, userId, name);
8107        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8108        // reader
8109        synchronized (mPackages) {
8110            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8111            PackageSetting ps = provider != null
8112                    ? mSettings.mPackages.get(provider.owner.packageName)
8113                    : null;
8114            if (ps != null) {
8115                final boolean isInstantApp = ps.getInstantApp(userId);
8116                // normal application; filter out instant application provider
8117                if (instantAppPkgName == null && isInstantApp) {
8118                    return null;
8119                }
8120                // instant application; filter out other instant applications
8121                if (instantAppPkgName != null
8122                        && isInstantApp
8123                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8124                    return null;
8125                }
8126                // instant application; filter out non-exposed provider
8127                if (instantAppPkgName != null
8128                        && !isInstantApp
8129                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8130                    return null;
8131                }
8132                // provider not enabled
8133                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8134                    return null;
8135                }
8136                return PackageParser.generateProviderInfo(
8137                        provider, flags, ps.readUserState(userId), userId);
8138            }
8139            return null;
8140        }
8141    }
8142
8143    /**
8144     * @deprecated
8145     */
8146    @Deprecated
8147    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8148        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8149            return;
8150        }
8151        // reader
8152        synchronized (mPackages) {
8153            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8154                    .entrySet().iterator();
8155            final int userId = UserHandle.getCallingUserId();
8156            while (i.hasNext()) {
8157                Map.Entry<String, PackageParser.Provider> entry = i.next();
8158                PackageParser.Provider p = entry.getValue();
8159                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8160
8161                if (ps != null && p.syncable
8162                        && (!mSafeMode || (p.info.applicationInfo.flags
8163                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8164                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8165                            ps.readUserState(userId), userId);
8166                    if (info != null) {
8167                        outNames.add(entry.getKey());
8168                        outInfo.add(info);
8169                    }
8170                }
8171            }
8172        }
8173    }
8174
8175    @Override
8176    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8177            int uid, int flags, String metaDataKey) {
8178        final int callingUid = Binder.getCallingUid();
8179        final int userId = processName != null ? UserHandle.getUserId(uid)
8180                : UserHandle.getCallingUserId();
8181        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8182        flags = updateFlagsForComponent(flags, userId, processName);
8183        ArrayList<ProviderInfo> finalList = null;
8184        // reader
8185        synchronized (mPackages) {
8186            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8187            while (i.hasNext()) {
8188                final PackageParser.Provider p = i.next();
8189                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8190                if (ps != null && p.info.authority != null
8191                        && (processName == null
8192                                || (p.info.processName.equals(processName)
8193                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8194                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8195
8196                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8197                    // parameter.
8198                    if (metaDataKey != null
8199                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8200                        continue;
8201                    }
8202                    final ComponentName component =
8203                            new ComponentName(p.info.packageName, p.info.name);
8204                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8205                        continue;
8206                    }
8207                    if (finalList == null) {
8208                        finalList = new ArrayList<ProviderInfo>(3);
8209                    }
8210                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8211                            ps.readUserState(userId), userId);
8212                    if (info != null) {
8213                        finalList.add(info);
8214                    }
8215                }
8216            }
8217        }
8218
8219        if (finalList != null) {
8220            Collections.sort(finalList, mProviderInitOrderSorter);
8221            return new ParceledListSlice<ProviderInfo>(finalList);
8222        }
8223
8224        return ParceledListSlice.emptyList();
8225    }
8226
8227    @Override
8228    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8229        // reader
8230        synchronized (mPackages) {
8231            final int callingUid = Binder.getCallingUid();
8232            final int callingUserId = UserHandle.getUserId(callingUid);
8233            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8234            if (ps == null) return null;
8235            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8236                return null;
8237            }
8238            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8239            return PackageParser.generateInstrumentationInfo(i, flags);
8240        }
8241    }
8242
8243    @Override
8244    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8245            String targetPackage, int flags) {
8246        final int callingUid = Binder.getCallingUid();
8247        final int callingUserId = UserHandle.getUserId(callingUid);
8248        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8249        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8250            return ParceledListSlice.emptyList();
8251        }
8252        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8253    }
8254
8255    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8256            int flags) {
8257        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8258
8259        // reader
8260        synchronized (mPackages) {
8261            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8262            while (i.hasNext()) {
8263                final PackageParser.Instrumentation p = i.next();
8264                if (targetPackage == null
8265                        || targetPackage.equals(p.info.targetPackage)) {
8266                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8267                            flags);
8268                    if (ii != null) {
8269                        finalList.add(ii);
8270                    }
8271                }
8272            }
8273        }
8274
8275        return finalList;
8276    }
8277
8278    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8279        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8280        try {
8281            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8282        } finally {
8283            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8284        }
8285    }
8286
8287    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8288        final File[] files = scanDir.listFiles();
8289        if (ArrayUtils.isEmpty(files)) {
8290            Log.d(TAG, "No files in app dir " + scanDir);
8291            return;
8292        }
8293
8294        if (DEBUG_PACKAGE_SCANNING) {
8295            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8296                    + " flags=0x" + Integer.toHexString(parseFlags));
8297        }
8298        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8299                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8300                mParallelPackageParserCallback)) {
8301            // Submit files for parsing in parallel
8302            int fileCount = 0;
8303            for (File file : files) {
8304                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8305                        && !PackageInstallerService.isStageName(file.getName());
8306                if (!isPackage) {
8307                    // Ignore entries which are not packages
8308                    continue;
8309                }
8310                parallelPackageParser.submit(file, parseFlags);
8311                fileCount++;
8312            }
8313
8314            // Process results one by one
8315            for (; fileCount > 0; fileCount--) {
8316                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8317                Throwable throwable = parseResult.throwable;
8318                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8319
8320                if (throwable == null) {
8321                    // TODO(toddke): move lower in the scan chain
8322                    // Static shared libraries have synthetic package names
8323                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8324                        renameStaticSharedLibraryPackage(parseResult.pkg);
8325                    }
8326                    try {
8327                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8328                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8329                                    currentTime, null);
8330                        }
8331                    } catch (PackageManagerException e) {
8332                        errorCode = e.error;
8333                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8334                    }
8335                } else if (throwable instanceof PackageParser.PackageParserException) {
8336                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8337                            throwable;
8338                    errorCode = e.error;
8339                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8340                } else {
8341                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8342                            + parseResult.scanFile, throwable);
8343                }
8344
8345                // Delete invalid userdata apps
8346                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8347                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8348                    logCriticalInfo(Log.WARN,
8349                            "Deleting invalid package at " + parseResult.scanFile);
8350                    removeCodePathLI(parseResult.scanFile);
8351                }
8352            }
8353        }
8354    }
8355
8356    public static void reportSettingsProblem(int priority, String msg) {
8357        logCriticalInfo(priority, msg);
8358    }
8359
8360    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8361            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8362        // When upgrading from pre-N MR1, verify the package time stamp using the package
8363        // directory and not the APK file.
8364        final long lastModifiedTime = mIsPreNMR1Upgrade
8365                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8366        if (ps != null && !forceCollect
8367                && ps.codePathString.equals(pkg.codePath)
8368                && ps.timeStamp == lastModifiedTime
8369                && !isCompatSignatureUpdateNeeded(pkg)
8370                && !isRecoverSignatureUpdateNeeded(pkg)) {
8371            if (ps.signatures.mSigningDetails.signatures != null
8372                    && ps.signatures.mSigningDetails.signatures.length != 0
8373                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8374                            != SignatureSchemeVersion.UNKNOWN) {
8375                // Optimization: reuse the existing cached signing data
8376                // if the package appears to be unchanged.
8377                pkg.mSigningDetails =
8378                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8379                return;
8380            }
8381
8382            Slog.w(TAG, "PackageSetting for " + ps.name
8383                    + " is missing signatures.  Collecting certs again to recover them.");
8384        } else {
8385            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8386                    (forceCollect ? " (forced)" : ""));
8387        }
8388
8389        try {
8390            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8391            PackageParser.collectCertificates(pkg, skipVerify);
8392        } catch (PackageParserException e) {
8393            throw PackageManagerException.from(e);
8394        } finally {
8395            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8396        }
8397    }
8398
8399    /**
8400     *  Traces a package scan.
8401     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8402     */
8403    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8404            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8405        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8406        try {
8407            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8408        } finally {
8409            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8410        }
8411    }
8412
8413    /**
8414     *  Scans a package and returns the newly parsed package.
8415     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8416     */
8417    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8418            long currentTime, UserHandle user) throws PackageManagerException {
8419        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8420        PackageParser pp = new PackageParser();
8421        pp.setSeparateProcesses(mSeparateProcesses);
8422        pp.setOnlyCoreApps(mOnlyCore);
8423        pp.setDisplayMetrics(mMetrics);
8424        pp.setCallback(mPackageParserCallback);
8425
8426        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8427        final PackageParser.Package pkg;
8428        try {
8429            pkg = pp.parsePackage(scanFile, parseFlags);
8430        } catch (PackageParserException e) {
8431            throw PackageManagerException.from(e);
8432        } finally {
8433            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8434        }
8435
8436        // Static shared libraries have synthetic package names
8437        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8438            renameStaticSharedLibraryPackage(pkg);
8439        }
8440
8441        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8442    }
8443
8444    /**
8445     *  Scans a package and returns the newly parsed package.
8446     *  @throws PackageManagerException on a parse error.
8447     */
8448    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8449            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8450            @Nullable UserHandle user)
8451                    throws PackageManagerException {
8452        // If the package has children and this is the first dive in the function
8453        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8454        // packages (parent and children) would be successfully scanned before the
8455        // actual scan since scanning mutates internal state and we want to atomically
8456        // install the package and its children.
8457        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8458            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8459                scanFlags |= SCAN_CHECK_ONLY;
8460            }
8461        } else {
8462            scanFlags &= ~SCAN_CHECK_ONLY;
8463        }
8464
8465        // Scan the parent
8466        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8467                scanFlags, currentTime, user);
8468
8469        // Scan the children
8470        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8471        for (int i = 0; i < childCount; i++) {
8472            PackageParser.Package childPackage = pkg.childPackages.get(i);
8473            addForInitLI(childPackage, parseFlags, scanFlags,
8474                    currentTime, user);
8475        }
8476
8477
8478        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8479            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8480        }
8481
8482        return scannedPkg;
8483    }
8484
8485    /**
8486     * Returns if full apk verification can be skipped for the whole package, including the splits.
8487     */
8488    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8489        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8490            return false;
8491        }
8492        // TODO: Allow base and splits to be verified individually.
8493        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8494            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8495                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8496                    return false;
8497                }
8498            }
8499        }
8500        return true;
8501    }
8502
8503    /**
8504     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8505     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8506     * match one in a trusted source, and should be done separately.
8507     */
8508    private boolean canSkipFullApkVerification(String apkPath) {
8509        byte[] rootHashObserved = null;
8510        try {
8511            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8512            if (rootHashObserved == null) {
8513                return false;  // APK does not contain Merkle tree root hash.
8514            }
8515            synchronized (mInstallLock) {
8516                // Returns whether the observed root hash matches what kernel has.
8517                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8518                return true;
8519            }
8520        } catch (InstallerException | IOException | DigestException |
8521                NoSuchAlgorithmException e) {
8522            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8523        }
8524        return false;
8525    }
8526
8527    /**
8528     * Adds a new package to the internal data structures during platform initialization.
8529     * <p>After adding, the package is known to the system and available for querying.
8530     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8531     * etc...], additional checks are performed. Basic verification [such as ensuring
8532     * matching signatures, checking version codes, etc...] occurs if the package is
8533     * identical to a previously known package. If the package fails a signature check,
8534     * the version installed on /data will be removed. If the version of the new package
8535     * is less than or equal than the version on /data, it will be ignored.
8536     * <p>Regardless of the package location, the results are applied to the internal
8537     * structures and the package is made available to the rest of the system.
8538     * <p>NOTE: The return value should be removed. It's the passed in package object.
8539     */
8540    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8541            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8542            @Nullable UserHandle user)
8543                    throws PackageManagerException {
8544        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8545        final String renamedPkgName;
8546        final PackageSetting disabledPkgSetting;
8547        final boolean isSystemPkgUpdated;
8548        final boolean pkgAlreadyExists;
8549        PackageSetting pkgSetting;
8550
8551        // NOTE: installPackageLI() has the same code to setup the package's
8552        // application info. This probably should be done lower in the call
8553        // stack [such as scanPackageOnly()]. However, we verify the application
8554        // info prior to that [in scanPackageNew()] and thus have to setup
8555        // the application info early.
8556        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8557        pkg.setApplicationInfoCodePath(pkg.codePath);
8558        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8559        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8560        pkg.setApplicationInfoResourcePath(pkg.codePath);
8561        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8562        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8563
8564        synchronized (mPackages) {
8565            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8566            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8567            if (realPkgName != null) {
8568                ensurePackageRenamed(pkg, renamedPkgName);
8569            }
8570            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8571            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8572            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8573            pkgAlreadyExists = pkgSetting != null;
8574            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8575            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8576            isSystemPkgUpdated = disabledPkgSetting != null;
8577
8578            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8579                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
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);
8592            }
8593
8594            if (scanSystemPartition) {
8595                // Potentially prune child packages. If the application on the /system
8596                // partition has been updated via OTA, but, is still disabled by a
8597                // version on /data, cycle through all of its children packages and
8598                // remove children that are no longer defined.
8599                if (isSystemPkgUpdated) {
8600                    final int scannedChildCount = (pkg.childPackages != null)
8601                            ? pkg.childPackages.size() : 0;
8602                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8603                            ? disabledPkgSetting.childPackageNames.size() : 0;
8604                    for (int i = 0; i < disabledChildCount; i++) {
8605                        String disabledChildPackageName =
8606                                disabledPkgSetting.childPackageNames.get(i);
8607                        boolean disabledPackageAvailable = false;
8608                        for (int j = 0; j < scannedChildCount; j++) {
8609                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8610                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8611                                disabledPackageAvailable = true;
8612                                break;
8613                            }
8614                        }
8615                        if (!disabledPackageAvailable) {
8616                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8617                        }
8618                    }
8619                    // we're updating the disabled package, so, scan it as the package setting
8620                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8621                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8622                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8623                            (pkg == mPlatformPackage), user);
8624                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8625                }
8626            }
8627        }
8628
8629        final boolean newPkgChangedPaths =
8630                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8631        final boolean newPkgVersionGreater =
8632                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8633        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8634                && newPkgChangedPaths && newPkgVersionGreater;
8635        if (isSystemPkgBetter) {
8636            // The version of the application on /system is greater than the version on
8637            // /data. Switch back to the application on /system.
8638            // It's safe to assume the application on /system will correctly scan. If not,
8639            // there won't be a working copy of the application.
8640            synchronized (mPackages) {
8641                // just remove the loaded entries from package lists
8642                mPackages.remove(pkgSetting.name);
8643            }
8644
8645            logCriticalInfo(Log.WARN,
8646                    "System package updated;"
8647                    + " name: " + pkgSetting.name
8648                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8649                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8650
8651            final InstallArgs args = createInstallArgsForExisting(
8652                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8653                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8654            args.cleanUpResourcesLI();
8655            synchronized (mPackages) {
8656                mSettings.enableSystemPackageLPw(pkgSetting.name);
8657            }
8658        }
8659
8660        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8661            // The version of the application on the /system partition is less than or
8662            // equal to the version on the /data partition. Throw an exception and use
8663            // the application already installed on the /data partition.
8664            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8665                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8666                    + " better than this " + pkg.getLongVersionCode());
8667        }
8668
8669        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8670        // force re-collecting certificate.
8671        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8672                disabledPkgSetting);
8673        // Full APK verification can be skipped during certificate collection, only if the file is
8674        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8675        // cases, only data in Signing Block is verified instead of the whole file.
8676        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8677                (forceCollect && canSkipFullPackageVerification(pkg));
8678        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8679
8680        boolean shouldHideSystemApp = false;
8681        // A new application appeared on /system, but, we already have a copy of
8682        // the application installed on /data.
8683        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8684                && !pkgSetting.isSystem()) {
8685
8686            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8687                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8688                logCriticalInfo(Log.WARN,
8689                        "System package signature mismatch;"
8690                        + " name: " + pkgSetting.name);
8691                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8692                        "scanPackageInternalLI")) {
8693                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8694                }
8695                pkgSetting = null;
8696            } else if (newPkgVersionGreater) {
8697                // The application on /system is newer than the application on /data.
8698                // Simply remove the application on /data [keeping application data]
8699                // and replace it with the version on /system.
8700                logCriticalInfo(Log.WARN,
8701                        "System package enabled;"
8702                        + " name: " + pkgSetting.name
8703                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8704                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8705                InstallArgs args = createInstallArgsForExisting(
8706                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8707                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8708                synchronized (mInstallLock) {
8709                    args.cleanUpResourcesLI();
8710                }
8711            } else {
8712                // The application on /system is older than the application on /data. Hide
8713                // the application on /system and the version on /data will be scanned later
8714                // and re-added like an update.
8715                shouldHideSystemApp = true;
8716                logCriticalInfo(Log.INFO,
8717                        "System package disabled;"
8718                        + " name: " + pkgSetting.name
8719                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8720                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8721            }
8722        }
8723
8724        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8725                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8726
8727        if (shouldHideSystemApp) {
8728            synchronized (mPackages) {
8729                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8730            }
8731        }
8732        return scannedPkg;
8733    }
8734
8735    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8736        // Derive the new package synthetic package name
8737        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8738                + pkg.staticSharedLibVersion);
8739    }
8740
8741    private static String fixProcessName(String defProcessName,
8742            String processName) {
8743        if (processName == null) {
8744            return defProcessName;
8745        }
8746        return processName;
8747    }
8748
8749    /**
8750     * Enforces that only the system UID or root's UID can call a method exposed
8751     * via Binder.
8752     *
8753     * @param message used as message if SecurityException is thrown
8754     * @throws SecurityException if the caller is not system or root
8755     */
8756    private static final void enforceSystemOrRoot(String message) {
8757        final int uid = Binder.getCallingUid();
8758        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8759            throw new SecurityException(message);
8760        }
8761    }
8762
8763    @Override
8764    public void performFstrimIfNeeded() {
8765        enforceSystemOrRoot("Only the system can request fstrim");
8766
8767        // Before everything else, see whether we need to fstrim.
8768        try {
8769            IStorageManager sm = PackageHelper.getStorageManager();
8770            if (sm != null) {
8771                boolean doTrim = false;
8772                final long interval = android.provider.Settings.Global.getLong(
8773                        mContext.getContentResolver(),
8774                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8775                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8776                if (interval > 0) {
8777                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8778                    if (timeSinceLast > interval) {
8779                        doTrim = true;
8780                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8781                                + "; running immediately");
8782                    }
8783                }
8784                if (doTrim) {
8785                    final boolean dexOptDialogShown;
8786                    synchronized (mPackages) {
8787                        dexOptDialogShown = mDexOptDialogShown;
8788                    }
8789                    if (!isFirstBoot() && dexOptDialogShown) {
8790                        try {
8791                            ActivityManager.getService().showBootMessage(
8792                                    mContext.getResources().getString(
8793                                            R.string.android_upgrading_fstrim), true);
8794                        } catch (RemoteException e) {
8795                        }
8796                    }
8797                    sm.runMaintenance();
8798                }
8799            } else {
8800                Slog.e(TAG, "storageManager service unavailable!");
8801            }
8802        } catch (RemoteException e) {
8803            // Can't happen; StorageManagerService is local
8804        }
8805    }
8806
8807    @Override
8808    public void updatePackagesIfNeeded() {
8809        enforceSystemOrRoot("Only the system can request package update");
8810
8811        // We need to re-extract after an OTA.
8812        boolean causeUpgrade = isUpgrade();
8813
8814        // First boot or factory reset.
8815        // Note: we also handle devices that are upgrading to N right now as if it is their
8816        //       first boot, as they do not have profile data.
8817        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8818
8819        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8820        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8821
8822        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8823            return;
8824        }
8825
8826        List<PackageParser.Package> pkgs;
8827        synchronized (mPackages) {
8828            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8829        }
8830
8831        final long startTime = System.nanoTime();
8832        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8833                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8834                    false /* bootComplete */);
8835
8836        final int elapsedTimeSeconds =
8837                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8838
8839        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8840        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8841        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8842        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8843        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8844    }
8845
8846    /*
8847     * Return the prebuilt profile path given a package base code path.
8848     */
8849    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8850        return pkg.baseCodePath + ".prof";
8851    }
8852
8853    /**
8854     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8855     * containing statistics about the invocation. The array consists of three elements,
8856     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8857     * and {@code numberOfPackagesFailed}.
8858     */
8859    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8860            final String compilerFilter, boolean bootComplete) {
8861
8862        int numberOfPackagesVisited = 0;
8863        int numberOfPackagesOptimized = 0;
8864        int numberOfPackagesSkipped = 0;
8865        int numberOfPackagesFailed = 0;
8866        final int numberOfPackagesToDexopt = pkgs.size();
8867
8868        for (PackageParser.Package pkg : pkgs) {
8869            numberOfPackagesVisited++;
8870
8871            boolean useProfileForDexopt = false;
8872
8873            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8874                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8875                // that are already compiled.
8876                File profileFile = new File(getPrebuildProfilePath(pkg));
8877                // Copy profile if it exists.
8878                if (profileFile.exists()) {
8879                    try {
8880                        // We could also do this lazily before calling dexopt in
8881                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8882                        // is that we don't have a good way to say "do this only once".
8883                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8884                                pkg.applicationInfo.uid, pkg.packageName,
8885                                ArtManager.getProfileName(null))) {
8886                            Log.e(TAG, "Installer failed to copy system profile!");
8887                        } else {
8888                            // Disabled as this causes speed-profile compilation during first boot
8889                            // even if things are already compiled.
8890                            // useProfileForDexopt = true;
8891                        }
8892                    } catch (Exception e) {
8893                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8894                                e);
8895                    }
8896                } else {
8897                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8898                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8899                    // minimize the number off apps being speed-profile compiled during first boot.
8900                    // The other paths will not change the filter.
8901                    if (disabledPs != null && disabledPs.pkg.isStub) {
8902                        // The package is the stub one, remove the stub suffix to get the normal
8903                        // package and APK names.
8904                        String systemProfilePath =
8905                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8906                        profileFile = new File(systemProfilePath);
8907                        // If we have a profile for a compressed APK, copy it to the reference
8908                        // location.
8909                        // Note that copying the profile here will cause it to override the
8910                        // reference profile every OTA even though the existing reference profile
8911                        // may have more data. We can't copy during decompression since the
8912                        // directories are not set up at that point.
8913                        if (profileFile.exists()) {
8914                            try {
8915                                // We could also do this lazily before calling dexopt in
8916                                // PackageDexOptimizer to prevent this happening on first boot. The
8917                                // issue is that we don't have a good way to say "do this only
8918                                // once".
8919                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8920                                        pkg.applicationInfo.uid, pkg.packageName,
8921                                        ArtManager.getProfileName(null))) {
8922                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8923                                } else {
8924                                    useProfileForDexopt = true;
8925                                }
8926                            } catch (Exception e) {
8927                                Log.e(TAG, "Failed to copy profile " +
8928                                        profileFile.getAbsolutePath() + " ", e);
8929                            }
8930                        }
8931                    }
8932                }
8933            }
8934
8935            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8936                if (DEBUG_DEXOPT) {
8937                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8938                }
8939                numberOfPackagesSkipped++;
8940                continue;
8941            }
8942
8943            if (DEBUG_DEXOPT) {
8944                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8945                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8946            }
8947
8948            if (showDialog) {
8949                try {
8950                    ActivityManager.getService().showBootMessage(
8951                            mContext.getResources().getString(R.string.android_upgrading_apk,
8952                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8953                } catch (RemoteException e) {
8954                }
8955                synchronized (mPackages) {
8956                    mDexOptDialogShown = true;
8957                }
8958            }
8959
8960            String pkgCompilerFilter = compilerFilter;
8961            if (useProfileForDexopt) {
8962                // Use background dexopt mode to try and use the profile. Note that this does not
8963                // guarantee usage of the profile.
8964                pkgCompilerFilter =
8965                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
8966                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
8967            }
8968
8969            // checkProfiles is false to avoid merging profiles during boot which
8970            // might interfere with background compilation (b/28612421).
8971            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8972            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8973            // trade-off worth doing to save boot time work.
8974            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8975            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8976                    pkg.packageName,
8977                    pkgCompilerFilter,
8978                    dexoptFlags));
8979
8980            switch (primaryDexOptStaus) {
8981                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8982                    numberOfPackagesOptimized++;
8983                    break;
8984                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8985                    numberOfPackagesSkipped++;
8986                    break;
8987                case PackageDexOptimizer.DEX_OPT_FAILED:
8988                    numberOfPackagesFailed++;
8989                    break;
8990                default:
8991                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
8992                    break;
8993            }
8994        }
8995
8996        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8997                numberOfPackagesFailed };
8998    }
8999
9000    @Override
9001    public void notifyPackageUse(String packageName, int reason) {
9002        synchronized (mPackages) {
9003            final int callingUid = Binder.getCallingUid();
9004            final int callingUserId = UserHandle.getUserId(callingUid);
9005            if (getInstantAppPackageName(callingUid) != null) {
9006                if (!isCallerSameApp(packageName, callingUid)) {
9007                    return;
9008                }
9009            } else {
9010                if (isInstantApp(packageName, callingUserId)) {
9011                    return;
9012                }
9013            }
9014            notifyPackageUseLocked(packageName, reason);
9015        }
9016    }
9017
9018    private void notifyPackageUseLocked(String packageName, int reason) {
9019        final PackageParser.Package p = mPackages.get(packageName);
9020        if (p == null) {
9021            return;
9022        }
9023        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9024    }
9025
9026    @Override
9027    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9028            List<String> classPaths, String loaderIsa) {
9029        int userId = UserHandle.getCallingUserId();
9030        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9031        if (ai == null) {
9032            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9033                + loadingPackageName + ", user=" + userId);
9034            return;
9035        }
9036        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9037    }
9038
9039    @Override
9040    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9041            IDexModuleRegisterCallback callback) {
9042        int userId = UserHandle.getCallingUserId();
9043        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9044        DexManager.RegisterDexModuleResult result;
9045        if (ai == null) {
9046            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9047                     " calling user. package=" + packageName + ", user=" + userId);
9048            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9049        } else {
9050            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9051        }
9052
9053        if (callback != null) {
9054            mHandler.post(() -> {
9055                try {
9056                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9057                } catch (RemoteException e) {
9058                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9059                }
9060            });
9061        }
9062    }
9063
9064    /**
9065     * Ask the package manager to perform a dex-opt with the given compiler filter.
9066     *
9067     * Note: exposed only for the shell command to allow moving packages explicitly to a
9068     *       definite state.
9069     */
9070    @Override
9071    public boolean performDexOptMode(String packageName,
9072            boolean checkProfiles, String targetCompilerFilter, boolean force,
9073            boolean bootComplete, String splitName) {
9074        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9075                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9076                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9077        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9078                splitName, flags));
9079    }
9080
9081    /**
9082     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9083     * secondary dex files belonging to the given package.
9084     *
9085     * Note: exposed only for the shell command to allow moving packages explicitly to a
9086     *       definite state.
9087     */
9088    @Override
9089    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9090            boolean force) {
9091        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9092                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9093                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9094                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9095        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9096    }
9097
9098    /*package*/ boolean performDexOpt(DexoptOptions options) {
9099        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9100            return false;
9101        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9102            return false;
9103        }
9104
9105        if (options.isDexoptOnlySecondaryDex()) {
9106            return mDexManager.dexoptSecondaryDex(options);
9107        } else {
9108            int dexoptStatus = performDexOptWithStatus(options);
9109            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9110        }
9111    }
9112
9113    /**
9114     * Perform dexopt on the given package and return one of following result:
9115     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9116     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9117     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9118     */
9119    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9120        return performDexOptTraced(options);
9121    }
9122
9123    private int performDexOptTraced(DexoptOptions options) {
9124        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9125        try {
9126            return performDexOptInternal(options);
9127        } finally {
9128            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9129        }
9130    }
9131
9132    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9133    // if the package can now be considered up to date for the given filter.
9134    private int performDexOptInternal(DexoptOptions options) {
9135        PackageParser.Package p;
9136        synchronized (mPackages) {
9137            p = mPackages.get(options.getPackageName());
9138            if (p == null) {
9139                // Package could not be found. Report failure.
9140                return PackageDexOptimizer.DEX_OPT_FAILED;
9141            }
9142            mPackageUsage.maybeWriteAsync(mPackages);
9143            mCompilerStats.maybeWriteAsync();
9144        }
9145        long callingId = Binder.clearCallingIdentity();
9146        try {
9147            synchronized (mInstallLock) {
9148                return performDexOptInternalWithDependenciesLI(p, options);
9149            }
9150        } finally {
9151            Binder.restoreCallingIdentity(callingId);
9152        }
9153    }
9154
9155    public ArraySet<String> getOptimizablePackages() {
9156        ArraySet<String> pkgs = new ArraySet<String>();
9157        synchronized (mPackages) {
9158            for (PackageParser.Package p : mPackages.values()) {
9159                if (PackageDexOptimizer.canOptimizePackage(p)) {
9160                    pkgs.add(p.packageName);
9161                }
9162            }
9163        }
9164        return pkgs;
9165    }
9166
9167    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9168            DexoptOptions options) {
9169        // Select the dex optimizer based on the force parameter.
9170        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9171        //       allocate an object here.
9172        PackageDexOptimizer pdo = options.isForce()
9173                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9174                : mPackageDexOptimizer;
9175
9176        // Dexopt all dependencies first. Note: we ignore the return value and march on
9177        // on errors.
9178        // Note that we are going to call performDexOpt on those libraries as many times as
9179        // they are referenced in packages. When we do a batch of performDexOpt (for example
9180        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9181        // and the first package that uses the library will dexopt it. The
9182        // others will see that the compiled code for the library is up to date.
9183        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9184        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9185        if (!deps.isEmpty()) {
9186            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9187                    options.getCompilerFilter(), options.getSplitName(),
9188                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9189            for (PackageParser.Package depPackage : deps) {
9190                // TODO: Analyze and investigate if we (should) profile libraries.
9191                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9192                        getOrCreateCompilerPackageStats(depPackage),
9193                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9194            }
9195        }
9196        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9197                getOrCreateCompilerPackageStats(p),
9198                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9199    }
9200
9201    /**
9202     * Reconcile the information we have about the secondary dex files belonging to
9203     * {@code packagName} and the actual dex files. For all dex files that were
9204     * deleted, update the internal records and delete the generated oat files.
9205     */
9206    @Override
9207    public void reconcileSecondaryDexFiles(String packageName) {
9208        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9209            return;
9210        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9211            return;
9212        }
9213        mDexManager.reconcileSecondaryDexFiles(packageName);
9214    }
9215
9216    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9217    // a reference there.
9218    /*package*/ DexManager getDexManager() {
9219        return mDexManager;
9220    }
9221
9222    /**
9223     * Execute the background dexopt job immediately.
9224     */
9225    @Override
9226    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9227        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9228            return false;
9229        }
9230        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9231    }
9232
9233    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9234        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9235                || p.usesStaticLibraries != null) {
9236            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9237            Set<String> collectedNames = new HashSet<>();
9238            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9239
9240            retValue.remove(p);
9241
9242            return retValue;
9243        } else {
9244            return Collections.emptyList();
9245        }
9246    }
9247
9248    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9249            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9250        if (!collectedNames.contains(p.packageName)) {
9251            collectedNames.add(p.packageName);
9252            collected.add(p);
9253
9254            if (p.usesLibraries != null) {
9255                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9256                        null, collected, collectedNames);
9257            }
9258            if (p.usesOptionalLibraries != null) {
9259                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9260                        null, collected, collectedNames);
9261            }
9262            if (p.usesStaticLibraries != null) {
9263                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9264                        p.usesStaticLibrariesVersions, collected, collectedNames);
9265            }
9266        }
9267    }
9268
9269    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9270            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9271        final int libNameCount = libs.size();
9272        for (int i = 0; i < libNameCount; i++) {
9273            String libName = libs.get(i);
9274            long version = (versions != null && versions.length == libNameCount)
9275                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9276            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9277            if (libPkg != null) {
9278                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9279            }
9280        }
9281    }
9282
9283    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9284        synchronized (mPackages) {
9285            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9286            if (libEntry != null) {
9287                return mPackages.get(libEntry.apk);
9288            }
9289            return null;
9290        }
9291    }
9292
9293    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9294        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9295        if (versionedLib == null) {
9296            return null;
9297        }
9298        return versionedLib.get(version);
9299    }
9300
9301    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9302        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9303                pkg.staticSharedLibName);
9304        if (versionedLib == null) {
9305            return null;
9306        }
9307        long previousLibVersion = -1;
9308        final int versionCount = versionedLib.size();
9309        for (int i = 0; i < versionCount; i++) {
9310            final long libVersion = versionedLib.keyAt(i);
9311            if (libVersion < pkg.staticSharedLibVersion) {
9312                previousLibVersion = Math.max(previousLibVersion, libVersion);
9313            }
9314        }
9315        if (previousLibVersion >= 0) {
9316            return versionedLib.get(previousLibVersion);
9317        }
9318        return null;
9319    }
9320
9321    public void shutdown() {
9322        mPackageUsage.writeNow(mPackages);
9323        mCompilerStats.writeNow();
9324        mDexManager.writePackageDexUsageNow();
9325    }
9326
9327    @Override
9328    public void dumpProfiles(String packageName) {
9329        PackageParser.Package pkg;
9330        synchronized (mPackages) {
9331            pkg = mPackages.get(packageName);
9332            if (pkg == null) {
9333                throw new IllegalArgumentException("Unknown package: " + packageName);
9334            }
9335        }
9336        /* Only the shell, root, or the app user should be able to dump profiles. */
9337        int callingUid = Binder.getCallingUid();
9338        if (callingUid != Process.SHELL_UID &&
9339            callingUid != Process.ROOT_UID &&
9340            callingUid != pkg.applicationInfo.uid) {
9341            throw new SecurityException("dumpProfiles");
9342        }
9343
9344        synchronized (mInstallLock) {
9345            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9346            mArtManagerService.dumpProfiles(pkg);
9347            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9348        }
9349    }
9350
9351    @Override
9352    public void forceDexOpt(String packageName) {
9353        enforceSystemOrRoot("forceDexOpt");
9354
9355        PackageParser.Package pkg;
9356        synchronized (mPackages) {
9357            pkg = mPackages.get(packageName);
9358            if (pkg == null) {
9359                throw new IllegalArgumentException("Unknown package: " + packageName);
9360            }
9361        }
9362
9363        synchronized (mInstallLock) {
9364            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9365
9366            // Whoever is calling forceDexOpt wants a compiled package.
9367            // Don't use profiles since that may cause compilation to be skipped.
9368            final int res = performDexOptInternalWithDependenciesLI(
9369                    pkg,
9370                    new DexoptOptions(packageName,
9371                            getDefaultCompilerFilter(),
9372                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9373
9374            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9375            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9376                throw new IllegalStateException("Failed to dexopt: " + res);
9377            }
9378        }
9379    }
9380
9381    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9382        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9383            Slog.w(TAG, "Unable to update from " + oldPkg.name
9384                    + " to " + newPkg.packageName
9385                    + ": old package not in system partition");
9386            return false;
9387        } else if (mPackages.get(oldPkg.name) != null) {
9388            Slog.w(TAG, "Unable to update from " + oldPkg.name
9389                    + " to " + newPkg.packageName
9390                    + ": old package still exists");
9391            return false;
9392        }
9393        return true;
9394    }
9395
9396    void removeCodePathLI(File codePath) {
9397        if (codePath.isDirectory()) {
9398            try {
9399                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9400            } catch (InstallerException e) {
9401                Slog.w(TAG, "Failed to remove code path", e);
9402            }
9403        } else {
9404            codePath.delete();
9405        }
9406    }
9407
9408    private int[] resolveUserIds(int userId) {
9409        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9410    }
9411
9412    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9413        if (pkg == null) {
9414            Slog.wtf(TAG, "Package was null!", new Throwable());
9415            return;
9416        }
9417        clearAppDataLeafLIF(pkg, userId, flags);
9418        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9419        for (int i = 0; i < childCount; i++) {
9420            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9421        }
9422
9423        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9424    }
9425
9426    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9427        final PackageSetting ps;
9428        synchronized (mPackages) {
9429            ps = mSettings.mPackages.get(pkg.packageName);
9430        }
9431        for (int realUserId : resolveUserIds(userId)) {
9432            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9433            try {
9434                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9435                        ceDataInode);
9436            } catch (InstallerException e) {
9437                Slog.w(TAG, String.valueOf(e));
9438            }
9439        }
9440    }
9441
9442    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9443        if (pkg == null) {
9444            Slog.wtf(TAG, "Package was null!", new Throwable());
9445            return;
9446        }
9447        destroyAppDataLeafLIF(pkg, userId, flags);
9448        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9449        for (int i = 0; i < childCount; i++) {
9450            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9451        }
9452    }
9453
9454    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9455        final PackageSetting ps;
9456        synchronized (mPackages) {
9457            ps = mSettings.mPackages.get(pkg.packageName);
9458        }
9459        for (int realUserId : resolveUserIds(userId)) {
9460            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9461            try {
9462                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9463                        ceDataInode);
9464            } catch (InstallerException e) {
9465                Slog.w(TAG, String.valueOf(e));
9466            }
9467            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9468        }
9469    }
9470
9471    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9472        if (pkg == null) {
9473            Slog.wtf(TAG, "Package was null!", new Throwable());
9474            return;
9475        }
9476        destroyAppProfilesLeafLIF(pkg);
9477        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9478        for (int i = 0; i < childCount; i++) {
9479            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9480        }
9481    }
9482
9483    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9484        try {
9485            mInstaller.destroyAppProfiles(pkg.packageName);
9486        } catch (InstallerException e) {
9487            Slog.w(TAG, String.valueOf(e));
9488        }
9489    }
9490
9491    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9492        if (pkg == null) {
9493            Slog.wtf(TAG, "Package was null!", new Throwable());
9494            return;
9495        }
9496        mArtManagerService.clearAppProfiles(pkg);
9497        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9498        for (int i = 0; i < childCount; i++) {
9499            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9500        }
9501    }
9502
9503    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9504            long lastUpdateTime) {
9505        // Set parent install/update time
9506        PackageSetting ps = (PackageSetting) pkg.mExtras;
9507        if (ps != null) {
9508            ps.firstInstallTime = firstInstallTime;
9509            ps.lastUpdateTime = lastUpdateTime;
9510        }
9511        // Set children install/update time
9512        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9513        for (int i = 0; i < childCount; i++) {
9514            PackageParser.Package childPkg = pkg.childPackages.get(i);
9515            ps = (PackageSetting) childPkg.mExtras;
9516            if (ps != null) {
9517                ps.firstInstallTime = firstInstallTime;
9518                ps.lastUpdateTime = lastUpdateTime;
9519            }
9520        }
9521    }
9522
9523    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9524            SharedLibraryEntry file,
9525            PackageParser.Package changingLib) {
9526        if (file.path != null) {
9527            usesLibraryFiles.add(file.path);
9528            return;
9529        }
9530        PackageParser.Package p = mPackages.get(file.apk);
9531        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9532            // If we are doing this while in the middle of updating a library apk,
9533            // then we need to make sure to use that new apk for determining the
9534            // dependencies here.  (We haven't yet finished committing the new apk
9535            // to the package manager state.)
9536            if (p == null || p.packageName.equals(changingLib.packageName)) {
9537                p = changingLib;
9538            }
9539        }
9540        if (p != null) {
9541            usesLibraryFiles.addAll(p.getAllCodePaths());
9542            if (p.usesLibraryFiles != null) {
9543                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9544            }
9545        }
9546    }
9547
9548    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9549            PackageParser.Package changingLib) throws PackageManagerException {
9550        if (pkg == null) {
9551            return;
9552        }
9553        // The collection used here must maintain the order of addition (so
9554        // that libraries are searched in the correct order) and must have no
9555        // duplicates.
9556        Set<String> usesLibraryFiles = null;
9557        if (pkg.usesLibraries != null) {
9558            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9559                    null, null, pkg.packageName, changingLib, true,
9560                    pkg.applicationInfo.targetSdkVersion, null);
9561        }
9562        if (pkg.usesStaticLibraries != null) {
9563            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9564                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9565                    pkg.packageName, changingLib, true,
9566                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9567        }
9568        if (pkg.usesOptionalLibraries != null) {
9569            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9570                    null, null, pkg.packageName, changingLib, false,
9571                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9572        }
9573        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9574            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9575        } else {
9576            pkg.usesLibraryFiles = null;
9577        }
9578    }
9579
9580    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9581            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9582            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9583            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9584            throws PackageManagerException {
9585        final int libCount = requestedLibraries.size();
9586        for (int i = 0; i < libCount; i++) {
9587            final String libName = requestedLibraries.get(i);
9588            final long libVersion = requiredVersions != null ? requiredVersions[i]
9589                    : SharedLibraryInfo.VERSION_UNDEFINED;
9590            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9591            if (libEntry == null) {
9592                if (required) {
9593                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9594                            "Package " + packageName + " requires unavailable shared library "
9595                                    + libName + "; failing!");
9596                } else if (DEBUG_SHARED_LIBRARIES) {
9597                    Slog.i(TAG, "Package " + packageName
9598                            + " desires unavailable shared library "
9599                            + libName + "; ignoring!");
9600                }
9601            } else {
9602                if (requiredVersions != null && requiredCertDigests != null) {
9603                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9604                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9605                            "Package " + packageName + " requires unavailable static shared"
9606                                    + " library " + libName + " version "
9607                                    + libEntry.info.getLongVersion() + "; failing!");
9608                    }
9609
9610                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9611                    if (libPkg == null) {
9612                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9613                                "Package " + packageName + " requires unavailable static shared"
9614                                        + " library; failing!");
9615                    }
9616
9617                    final String[] expectedCertDigests = requiredCertDigests[i];
9618
9619
9620                    if (expectedCertDigests.length > 1) {
9621
9622                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9623                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9624                                ? PackageUtils.computeSignaturesSha256Digests(
9625                                libPkg.mSigningDetails.signatures)
9626                                : PackageUtils.computeSignaturesSha256Digests(
9627                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9628
9629                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9630                        // target O we don't parse the "additional-certificate" tags similarly
9631                        // how we only consider all certs only for apps targeting O (see above).
9632                        // Therefore, the size check is safe to make.
9633                        if (expectedCertDigests.length != libCertDigests.length) {
9634                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9635                                    "Package " + packageName + " requires differently signed" +
9636                                            " static shared library; failing!");
9637                        }
9638
9639                        // Use a predictable order as signature order may vary
9640                        Arrays.sort(libCertDigests);
9641                        Arrays.sort(expectedCertDigests);
9642
9643                        final int certCount = libCertDigests.length;
9644                        for (int j = 0; j < certCount; j++) {
9645                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9646                                throw new PackageManagerException(
9647                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9648                                        "Package " + packageName + " requires differently signed" +
9649                                                " static shared library; failing!");
9650                            }
9651                        }
9652                    } else {
9653
9654                        // lib signing cert could have rotated beyond the one expected, check to see
9655                        // if the new one has been blessed by the old
9656                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9657                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9658                            throw new PackageManagerException(
9659                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9660                                    "Package " + packageName + " requires differently signed" +
9661                                            " static shared library; failing!");
9662                        }
9663                    }
9664                }
9665
9666                if (outUsedLibraries == null) {
9667                    // Use LinkedHashSet to preserve the order of files added to
9668                    // usesLibraryFiles while eliminating duplicates.
9669                    outUsedLibraries = new LinkedHashSet<>();
9670                }
9671                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9672            }
9673        }
9674        return outUsedLibraries;
9675    }
9676
9677    private static boolean hasString(List<String> list, List<String> which) {
9678        if (list == null) {
9679            return false;
9680        }
9681        for (int i=list.size()-1; i>=0; i--) {
9682            for (int j=which.size()-1; j>=0; j--) {
9683                if (which.get(j).equals(list.get(i))) {
9684                    return true;
9685                }
9686            }
9687        }
9688        return false;
9689    }
9690
9691    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9692            PackageParser.Package changingPkg) {
9693        ArrayList<PackageParser.Package> res = null;
9694        for (PackageParser.Package pkg : mPackages.values()) {
9695            if (changingPkg != null
9696                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9697                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9698                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9699                            changingPkg.staticSharedLibName)) {
9700                return null;
9701            }
9702            if (res == null) {
9703                res = new ArrayList<>();
9704            }
9705            res.add(pkg);
9706            try {
9707                updateSharedLibrariesLPr(pkg, changingPkg);
9708            } catch (PackageManagerException e) {
9709                // If a system app update or an app and a required lib missing we
9710                // delete the package and for updated system apps keep the data as
9711                // it is better for the user to reinstall than to be in an limbo
9712                // state. Also libs disappearing under an app should never happen
9713                // - just in case.
9714                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9715                    final int flags = pkg.isUpdatedSystemApp()
9716                            ? PackageManager.DELETE_KEEP_DATA : 0;
9717                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9718                            flags , null, true, null);
9719                }
9720                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9721            }
9722        }
9723        return res;
9724    }
9725
9726    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9727            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9728            @Nullable UserHandle user) throws PackageManagerException {
9729        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9730        // If the package has children and this is the first dive in the function
9731        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9732        // whether all packages (parent and children) would be successfully scanned
9733        // before the actual scan since scanning mutates internal state and we want
9734        // to atomically install the package and its children.
9735        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9736            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9737                scanFlags |= SCAN_CHECK_ONLY;
9738            }
9739        } else {
9740            scanFlags &= ~SCAN_CHECK_ONLY;
9741        }
9742
9743        final PackageParser.Package scannedPkg;
9744        try {
9745            // Scan the parent
9746            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9747            // Scan the children
9748            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9749            for (int i = 0; i < childCount; i++) {
9750                PackageParser.Package childPkg = pkg.childPackages.get(i);
9751                scanPackageNewLI(childPkg, parseFlags,
9752                        scanFlags, currentTime, user);
9753            }
9754        } finally {
9755            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9756        }
9757
9758        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9759            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9760        }
9761
9762        return scannedPkg;
9763    }
9764
9765    /** The result of a package scan. */
9766    private static class ScanResult {
9767        /** Whether or not the package scan was successful */
9768        public final boolean success;
9769        /**
9770         * The final package settings. This may be the same object passed in
9771         * the {@link ScanRequest}, but, with modified values.
9772         */
9773        @Nullable public final PackageSetting pkgSetting;
9774        /** ABI code paths that have changed in the package scan */
9775        @Nullable public final List<String> changedAbiCodePath;
9776        public ScanResult(
9777                boolean success,
9778                @Nullable PackageSetting pkgSetting,
9779                @Nullable List<String> changedAbiCodePath) {
9780            this.success = success;
9781            this.pkgSetting = pkgSetting;
9782            this.changedAbiCodePath = changedAbiCodePath;
9783        }
9784    }
9785
9786    /** A package to be scanned */
9787    private static class ScanRequest {
9788        /** The parsed package */
9789        @NonNull public final PackageParser.Package pkg;
9790        /** Shared user settings, if the package has a shared user */
9791        @Nullable public final SharedUserSetting sharedUserSetting;
9792        /**
9793         * Package settings of the currently installed version.
9794         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9795         * during scan.
9796         */
9797        @Nullable public final PackageSetting pkgSetting;
9798        /** A copy of the settings for the currently installed version */
9799        @Nullable public final PackageSetting oldPkgSetting;
9800        /** Package settings for the disabled version on the /system partition */
9801        @Nullable public final PackageSetting disabledPkgSetting;
9802        /** Package settings for the installed version under its original package name */
9803        @Nullable public final PackageSetting originalPkgSetting;
9804        /** The real package name of a renamed application */
9805        @Nullable public final String realPkgName;
9806        public final @ParseFlags int parseFlags;
9807        public final @ScanFlags int scanFlags;
9808        /** The user for which the package is being scanned */
9809        @Nullable public final UserHandle user;
9810        /** Whether or not the platform package is being scanned */
9811        public final boolean isPlatformPackage;
9812        public ScanRequest(
9813                @NonNull PackageParser.Package pkg,
9814                @Nullable SharedUserSetting sharedUserSetting,
9815                @Nullable PackageSetting pkgSetting,
9816                @Nullable PackageSetting disabledPkgSetting,
9817                @Nullable PackageSetting originalPkgSetting,
9818                @Nullable String realPkgName,
9819                @ParseFlags int parseFlags,
9820                @ScanFlags int scanFlags,
9821                boolean isPlatformPackage,
9822                @Nullable UserHandle user) {
9823            this.pkg = pkg;
9824            this.pkgSetting = pkgSetting;
9825            this.sharedUserSetting = sharedUserSetting;
9826            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9827            this.disabledPkgSetting = disabledPkgSetting;
9828            this.originalPkgSetting = originalPkgSetting;
9829            this.realPkgName = realPkgName;
9830            this.parseFlags = parseFlags;
9831            this.scanFlags = scanFlags;
9832            this.isPlatformPackage = isPlatformPackage;
9833            this.user = user;
9834        }
9835    }
9836
9837    /**
9838     * Returns the actual scan flags depending upon the state of the other settings.
9839     * <p>Updated system applications will not have the following flags set
9840     * by default and need to be adjusted after the fact:
9841     * <ul>
9842     * <li>{@link #SCAN_AS_SYSTEM}</li>
9843     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9844     * <li>{@link #SCAN_AS_OEM}</li>
9845     * <li>{@link #SCAN_AS_VENDOR}</li>
9846     * <li>{@link #SCAN_AS_PRODUCT}</li>
9847     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9848     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9849     * </ul>
9850     */
9851    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9852            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9853            PackageParser.Package pkg) {
9854        if (disabledPkgSetting != null) {
9855            // updated system application, must at least have SCAN_AS_SYSTEM
9856            scanFlags |= SCAN_AS_SYSTEM;
9857            if ((disabledPkgSetting.pkgPrivateFlags
9858                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9859                scanFlags |= SCAN_AS_PRIVILEGED;
9860            }
9861            if ((disabledPkgSetting.pkgPrivateFlags
9862                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9863                scanFlags |= SCAN_AS_OEM;
9864            }
9865            if ((disabledPkgSetting.pkgPrivateFlags
9866                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9867                scanFlags |= SCAN_AS_VENDOR;
9868            }
9869            if ((disabledPkgSetting.pkgPrivateFlags
9870                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9871                scanFlags |= SCAN_AS_PRODUCT;
9872            }
9873        }
9874        if (pkgSetting != null) {
9875            final int userId = ((user == null) ? 0 : user.getIdentifier());
9876            if (pkgSetting.getInstantApp(userId)) {
9877                scanFlags |= SCAN_AS_INSTANT_APP;
9878            }
9879            if (pkgSetting.getVirtulalPreload(userId)) {
9880                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9881            }
9882        }
9883
9884        // Scan as privileged apps that share a user with a priv-app.
9885        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9886                && (pkg.mSharedUserId != null)) {
9887            SharedUserSetting sharedUserSetting = null;
9888            try {
9889                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9890            } catch (PackageManagerException ignore) {}
9891            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9892                // Exempt SharedUsers signed with the platform key.
9893                // TODO(b/72378145) Fix this exemption. Force signature apps
9894                // to whitelist their privileged permissions just like other
9895                // priv-apps.
9896                synchronized (mPackages) {
9897                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9898                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9899                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9900                        scanFlags |= SCAN_AS_PRIVILEGED;
9901                    }
9902                }
9903            }
9904        }
9905
9906        return scanFlags;
9907    }
9908
9909    @GuardedBy("mInstallLock")
9910    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9911            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9912            @Nullable UserHandle user) throws PackageManagerException {
9913
9914        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9915        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9916        if (realPkgName != null) {
9917            ensurePackageRenamed(pkg, renamedPkgName);
9918        }
9919        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9920        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9921        final PackageSetting disabledPkgSetting =
9922                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9923
9924        if (mTransferedPackages.contains(pkg.packageName)) {
9925            Slog.w(TAG, "Package " + pkg.packageName
9926                    + " was transferred to another, but its .apk remains");
9927        }
9928
9929        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
9930        synchronized (mPackages) {
9931            applyPolicy(pkg, parseFlags, scanFlags);
9932            assertPackageIsValid(pkg, parseFlags, scanFlags);
9933
9934            SharedUserSetting sharedUserSetting = null;
9935            if (pkg.mSharedUserId != null) {
9936                // SIDE EFFECTS; may potentially allocate a new shared user
9937                sharedUserSetting = mSettings.getSharedUserLPw(
9938                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9939                if (DEBUG_PACKAGE_SCANNING) {
9940                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9941                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
9942                                + " (uid=" + sharedUserSetting.userId + "):"
9943                                + " packages=" + sharedUserSetting.packages);
9944                }
9945            }
9946
9947            boolean scanSucceeded = false;
9948            try {
9949                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
9950                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
9951                        (pkg == mPlatformPackage), user);
9952                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
9953                if (result.success) {
9954                    commitScanResultsLocked(request, result);
9955                }
9956                scanSucceeded = true;
9957            } finally {
9958                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9959                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
9960                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9961                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9962                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9963                  }
9964            }
9965        }
9966        return pkg;
9967    }
9968
9969    /**
9970     * Commits the package scan and modifies system state.
9971     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
9972     * of committing the package, leaving the system in an inconsistent state.
9973     * This needs to be fixed so, once we get to this point, no errors are
9974     * possible and the system is not left in an inconsistent state.
9975     */
9976    @GuardedBy("mPackages")
9977    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
9978            throws PackageManagerException {
9979        final PackageParser.Package pkg = request.pkg;
9980        final @ParseFlags int parseFlags = request.parseFlags;
9981        final @ScanFlags int scanFlags = request.scanFlags;
9982        final PackageSetting oldPkgSetting = request.oldPkgSetting;
9983        final PackageSetting originalPkgSetting = request.originalPkgSetting;
9984        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
9985        final UserHandle user = request.user;
9986        final String realPkgName = request.realPkgName;
9987        final PackageSetting pkgSetting = result.pkgSetting;
9988        final List<String> changedAbiCodePath = result.changedAbiCodePath;
9989        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
9990
9991        if (newPkgSettingCreated) {
9992            if (originalPkgSetting != null) {
9993                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
9994            }
9995            // THROWS: when we can't allocate a user id. add call to check if there's
9996            // enough space to ensure we won't throw; otherwise, don't modify state
9997            mSettings.addUserToSettingLPw(pkgSetting);
9998
9999            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10000                mTransferedPackages.add(originalPkgSetting.name);
10001            }
10002        }
10003        // TODO(toddke): Consider a method specifically for modifying the Package object
10004        // post scan; or, moving this stuff out of the Package object since it has nothing
10005        // to do with the package on disk.
10006        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10007        // for creating the application ID. If we did this earlier, we would be saving the
10008        // correct ID.
10009        pkg.applicationInfo.uid = pkgSetting.appId;
10010
10011        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10012
10013        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10014            mTransferedPackages.add(pkg.packageName);
10015        }
10016
10017        // THROWS: when requested libraries that can't be found. it only changes
10018        // the state of the passed in pkg object, so, move to the top of the method
10019        // and allow it to abort
10020        if ((scanFlags & SCAN_BOOTING) == 0
10021                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10022            // Check all shared libraries and map to their actual file path.
10023            // We only do this here for apps not on a system dir, because those
10024            // are the only ones that can fail an install due to this.  We
10025            // will take care of the system apps by updating all of their
10026            // library paths after the scan is done. Also during the initial
10027            // scan don't update any libs as we do this wholesale after all
10028            // apps are scanned to avoid dependency based scanning.
10029            updateSharedLibrariesLPr(pkg, null);
10030        }
10031
10032        // All versions of a static shared library are referenced with the same
10033        // package name. Internally, we use a synthetic package name to allow
10034        // multiple versions of the same shared library to be installed. So,
10035        // we need to generate the synthetic package name of the latest shared
10036        // library in order to compare signatures.
10037        PackageSetting signatureCheckPs = pkgSetting;
10038        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10039            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10040            if (libraryEntry != null) {
10041                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10042            }
10043        }
10044
10045        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10046        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10047            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10048                // We just determined the app is signed correctly, so bring
10049                // over the latest parsed certs.
10050                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10051            } else {
10052                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10053                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10054                            "Package " + pkg.packageName + " upgrade keys do not match the "
10055                                    + "previously installed version");
10056                } else {
10057                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10058                    String msg = "System package " + pkg.packageName
10059                            + " signature changed; retaining data.";
10060                    reportSettingsProblem(Log.WARN, msg);
10061                }
10062            }
10063        } else {
10064            try {
10065                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10066                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10067                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10068                        pkg.mSigningDetails, compareCompat, compareRecover);
10069                // The new KeySets will be re-added later in the scanning process.
10070                if (compatMatch) {
10071                    synchronized (mPackages) {
10072                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10073                    }
10074                }
10075                // We just determined the app is signed correctly, so bring
10076                // over the latest parsed certs.
10077                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10078
10079
10080                // if this is is a sharedUser, check to see if the new package is signed by a newer
10081                // signing certificate than the existing one, and if so, copy over the new details
10082                if (signatureCheckPs.sharedUser != null
10083                        && pkg.mSigningDetails.hasAncestor(
10084                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10085                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10086                }
10087            } catch (PackageManagerException e) {
10088                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10089                    throw e;
10090                }
10091                // The signature has changed, but this package is in the system
10092                // image...  let's recover!
10093                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10094                // However...  if this package is part of a shared user, but it
10095                // doesn't match the signature of the shared user, let's fail.
10096                // What this means is that you can't change the signatures
10097                // associated with an overall shared user, which doesn't seem all
10098                // that unreasonable.
10099                if (signatureCheckPs.sharedUser != null) {
10100                    if (compareSignatures(
10101                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10102                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10103                        throw new PackageManagerException(
10104                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10105                                "Signature mismatch for shared user: "
10106                                        + pkgSetting.sharedUser);
10107                    }
10108                }
10109                // File a report about this.
10110                String msg = "System package " + pkg.packageName
10111                        + " signature changed; retaining data.";
10112                reportSettingsProblem(Log.WARN, msg);
10113            } catch (IllegalArgumentException e) {
10114
10115                // should never happen: certs matched when checking, but not when comparing
10116                // old to new for sharedUser
10117                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10118                        "Signing certificates comparison made on incomparable signing details"
10119                        + " but somehow passed verifySignatures!");
10120            }
10121        }
10122
10123        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10124            // This package wants to adopt ownership of permissions from
10125            // another package.
10126            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10127                final String origName = pkg.mAdoptPermissions.get(i);
10128                final PackageSetting orig = mSettings.getPackageLPr(origName);
10129                if (orig != null) {
10130                    if (verifyPackageUpdateLPr(orig, pkg)) {
10131                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10132                                + pkg.packageName);
10133                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10134                    }
10135                }
10136            }
10137        }
10138
10139        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10140            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10141                final String codePathString = changedAbiCodePath.get(i);
10142                try {
10143                    mInstaller.rmdex(codePathString,
10144                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10145                } catch (InstallerException ignored) {
10146                }
10147            }
10148        }
10149
10150        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10151            if (oldPkgSetting != null) {
10152                synchronized (mPackages) {
10153                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10154                }
10155            }
10156        } else {
10157            final int userId = user == null ? 0 : user.getIdentifier();
10158            // Modify state for the given package setting
10159            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10160                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10161            if (pkgSetting.getInstantApp(userId)) {
10162                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10163            }
10164        }
10165    }
10166
10167    /**
10168     * Returns the "real" name of the package.
10169     * <p>This may differ from the package's actual name if the application has already
10170     * been installed under one of this package's original names.
10171     */
10172    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10173            @Nullable String renamedPkgName) {
10174        if (isPackageRenamed(pkg, renamedPkgName)) {
10175            return pkg.mRealPackage;
10176        }
10177        return null;
10178    }
10179
10180    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10181    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10182            @Nullable String renamedPkgName) {
10183        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10184    }
10185
10186    /**
10187     * Returns the original package setting.
10188     * <p>A package can migrate its name during an update. In this scenario, a package
10189     * designates a set of names that it considers as one of its original names.
10190     * <p>An original package must be signed identically and it must have the same
10191     * shared user [if any].
10192     */
10193    @GuardedBy("mPackages")
10194    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10195            @Nullable String renamedPkgName) {
10196        if (!isPackageRenamed(pkg, renamedPkgName)) {
10197            return null;
10198        }
10199        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10200            final PackageSetting originalPs =
10201                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10202            if (originalPs != null) {
10203                // the package is already installed under its original name...
10204                // but, should we use it?
10205                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10206                    // the new package is incompatible with the original
10207                    continue;
10208                } else if (originalPs.sharedUser != null) {
10209                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10210                        // the shared user id is incompatible with the original
10211                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10212                                + " to " + pkg.packageName + ": old uid "
10213                                + originalPs.sharedUser.name
10214                                + " differs from " + pkg.mSharedUserId);
10215                        continue;
10216                    }
10217                    // TODO: Add case when shared user id is added [b/28144775]
10218                } else {
10219                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10220                            + pkg.packageName + " to old name " + originalPs.name);
10221                }
10222                return originalPs;
10223            }
10224        }
10225        return null;
10226    }
10227
10228    /**
10229     * Renames the package if it was installed under a different name.
10230     * <p>When we've already installed the package under an original name, update
10231     * the new package so we can continue to have the old name.
10232     */
10233    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10234            @NonNull String renamedPackageName) {
10235        if (pkg.mOriginalPackages == null
10236                || !pkg.mOriginalPackages.contains(renamedPackageName)
10237                || pkg.packageName.equals(renamedPackageName)) {
10238            return;
10239        }
10240        pkg.setPackageName(renamedPackageName);
10241    }
10242
10243    /**
10244     * Just scans the package without any side effects.
10245     * <p>Not entirely true at the moment. There is still one side effect -- this
10246     * method potentially modifies a live {@link PackageSetting} object representing
10247     * the package being scanned. This will be resolved in the future.
10248     *
10249     * @param request Information about the package to be scanned
10250     * @param isUnderFactoryTest Whether or not the device is under factory test
10251     * @param currentTime The current time, in millis
10252     * @return The results of the scan
10253     */
10254    @GuardedBy("mInstallLock")
10255    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10256            boolean isUnderFactoryTest, long currentTime)
10257                    throws PackageManagerException {
10258        final PackageParser.Package pkg = request.pkg;
10259        PackageSetting pkgSetting = request.pkgSetting;
10260        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10261        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10262        final @ParseFlags int parseFlags = request.parseFlags;
10263        final @ScanFlags int scanFlags = request.scanFlags;
10264        final String realPkgName = request.realPkgName;
10265        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10266        final UserHandle user = request.user;
10267        final boolean isPlatformPackage = request.isPlatformPackage;
10268
10269        List<String> changedAbiCodePath = null;
10270
10271        if (DEBUG_PACKAGE_SCANNING) {
10272            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10273                Log.d(TAG, "Scanning package " + pkg.packageName);
10274        }
10275
10276        if (Build.IS_DEBUGGABLE &&
10277                pkg.isPrivileged() &&
10278                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10279            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10280        }
10281
10282        // Initialize package source and resource directories
10283        final File scanFile = new File(pkg.codePath);
10284        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10285        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10286
10287        // We keep references to the derived CPU Abis from settings in oder to reuse
10288        // them in the case where we're not upgrading or booting for the first time.
10289        String primaryCpuAbiFromSettings = null;
10290        String secondaryCpuAbiFromSettings = null;
10291        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10292
10293        if (!needToDeriveAbi) {
10294            if (pkgSetting != null) {
10295                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10296                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10297            } else {
10298                // Re-scanning a system package after uninstalling updates; need to derive ABI
10299                needToDeriveAbi = true;
10300            }
10301        }
10302
10303        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10304            PackageManagerService.reportSettingsProblem(Log.WARN,
10305                    "Package " + pkg.packageName + " shared user changed from "
10306                            + (pkgSetting.sharedUser != null
10307                            ? pkgSetting.sharedUser.name : "<nothing>")
10308                            + " to "
10309                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10310                            + "; replacing with new");
10311            pkgSetting = null;
10312        }
10313
10314        String[] usesStaticLibraries = null;
10315        if (pkg.usesStaticLibraries != null) {
10316            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10317            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10318        }
10319        final boolean createNewPackage = (pkgSetting == null);
10320        if (createNewPackage) {
10321            final String parentPackageName = (pkg.parentPackage != null)
10322                    ? pkg.parentPackage.packageName : null;
10323            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10324            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10325            // REMOVE SharedUserSetting from method; update in a separate call
10326            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10327                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10328                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10329                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10330                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10331                    user, true /*allowInstall*/, instantApp, virtualPreload,
10332                    parentPackageName, pkg.getChildPackageNames(),
10333                    UserManagerService.getInstance(), usesStaticLibraries,
10334                    pkg.usesStaticLibrariesVersions);
10335        } else {
10336            // REMOVE SharedUserSetting from method; update in a separate call.
10337            //
10338            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10339            // secondaryCpuAbi are not known at this point so we always update them
10340            // to null here, only to reset them at a later point.
10341            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10342                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10343                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10344                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10345                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10346                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10347        }
10348        if (createNewPackage && originalPkgSetting != null) {
10349            // This is the initial transition from the original package, so,
10350            // fix up the new package's name now. We must do this after looking
10351            // up the package under its new name, so getPackageLP takes care of
10352            // fiddling things correctly.
10353            pkg.setPackageName(originalPkgSetting.name);
10354
10355            // File a report about this.
10356            String msg = "New package " + pkgSetting.realName
10357                    + " renamed to replace old package " + pkgSetting.name;
10358            reportSettingsProblem(Log.WARN, msg);
10359        }
10360
10361        if (disabledPkgSetting != null) {
10362            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10363        }
10364
10365        // SELinux sandboxes become more restrictive as targetSdkVersion increases.
10366        // To ensure that apps with sharedUserId are placed in the same selinux domain
10367        // without breaking any assumptions about access, put them into the least
10368        // restrictive targetSdkVersion=25 domain.
10369        // TODO(b/72290969): Base this on the actual targetSdkVersion(s) of the apps within the
10370        // sharedUserSetting, instead of defaulting to the least restrictive domain.
10371        final int targetSdk = (sharedUserSetting != null) ? 25
10372                : pkg.applicationInfo.targetSdkVersion;
10373        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10374        // They currently can be if the sharedUser apps are signed with the platform key.
10375        final boolean isPrivileged = (sharedUserSetting != null) ?
10376            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10377
10378        SELinuxMMAC.assignSeInfoValue(pkg, isPrivileged, targetSdk);
10379
10380        pkg.mExtras = pkgSetting;
10381        pkg.applicationInfo.processName = fixProcessName(
10382                pkg.applicationInfo.packageName,
10383                pkg.applicationInfo.processName);
10384
10385        if (!isPlatformPackage) {
10386            // Get all of our default paths setup
10387            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10388        }
10389
10390        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10391
10392        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10393            if (needToDeriveAbi) {
10394                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10395                final boolean extractNativeLibs = !pkg.isLibrary();
10396                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10397                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10398
10399                // Some system apps still use directory structure for native libraries
10400                // in which case we might end up not detecting abi solely based on apk
10401                // structure. Try to detect abi based on directory structure.
10402                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10403                        pkg.applicationInfo.primaryCpuAbi == null) {
10404                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10405                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10406                }
10407            } else {
10408                // This is not a first boot or an upgrade, don't bother deriving the
10409                // ABI during the scan. Instead, trust the value that was stored in the
10410                // package setting.
10411                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10412                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10413
10414                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10415
10416                if (DEBUG_ABI_SELECTION) {
10417                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10418                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10419                            pkg.applicationInfo.secondaryCpuAbi);
10420                }
10421            }
10422        } else {
10423            if ((scanFlags & SCAN_MOVE) != 0) {
10424                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10425                // but we already have this packages package info in the PackageSetting. We just
10426                // use that and derive the native library path based on the new codepath.
10427                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10428                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10429            }
10430
10431            // Set native library paths again. For moves, the path will be updated based on the
10432            // ABIs we've determined above. For non-moves, the path will be updated based on the
10433            // ABIs we determined during compilation, but the path will depend on the final
10434            // package path (after the rename away from the stage path).
10435            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10436        }
10437
10438        // This is a special case for the "system" package, where the ABI is
10439        // dictated by the zygote configuration (and init.rc). We should keep track
10440        // of this ABI so that we can deal with "normal" applications that run under
10441        // the same UID correctly.
10442        if (isPlatformPackage) {
10443            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10444                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10445        }
10446
10447        // If there's a mismatch between the abi-override in the package setting
10448        // and the abiOverride specified for the install. Warn about this because we
10449        // would've already compiled the app without taking the package setting into
10450        // account.
10451        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10452            if (cpuAbiOverride == null && pkg.packageName != null) {
10453                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10454                        " for package " + pkg.packageName);
10455            }
10456        }
10457
10458        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10459        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10460        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10461
10462        // Copy the derived override back to the parsed package, so that we can
10463        // update the package settings accordingly.
10464        pkg.cpuAbiOverride = cpuAbiOverride;
10465
10466        if (DEBUG_ABI_SELECTION) {
10467            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10468                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10469                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10470        }
10471
10472        // Push the derived path down into PackageSettings so we know what to
10473        // clean up at uninstall time.
10474        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10475
10476        if (DEBUG_ABI_SELECTION) {
10477            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10478                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10479                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10480        }
10481
10482        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10483            // We don't do this here during boot because we can do it all
10484            // at once after scanning all existing packages.
10485            //
10486            // We also do this *before* we perform dexopt on this package, so that
10487            // we can avoid redundant dexopts, and also to make sure we've got the
10488            // code and package path correct.
10489            changedAbiCodePath =
10490                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10491        }
10492
10493        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10494                android.Manifest.permission.FACTORY_TEST)) {
10495            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10496        }
10497
10498        if (isSystemApp(pkg)) {
10499            pkgSetting.isOrphaned = true;
10500        }
10501
10502        // Take care of first install / last update times.
10503        final long scanFileTime = getLastModifiedTime(pkg);
10504        if (currentTime != 0) {
10505            if (pkgSetting.firstInstallTime == 0) {
10506                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10507            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10508                pkgSetting.lastUpdateTime = currentTime;
10509            }
10510        } else if (pkgSetting.firstInstallTime == 0) {
10511            // We need *something*.  Take time time stamp of the file.
10512            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10513        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10514            if (scanFileTime != pkgSetting.timeStamp) {
10515                // A package on the system image has changed; consider this
10516                // to be an update.
10517                pkgSetting.lastUpdateTime = scanFileTime;
10518            }
10519        }
10520        pkgSetting.setTimeStamp(scanFileTime);
10521
10522        pkgSetting.pkg = pkg;
10523        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10524        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10525            pkgSetting.versionCode = pkg.getLongVersionCode();
10526        }
10527        // Update volume if needed
10528        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10529        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10530            Slog.i(PackageManagerService.TAG,
10531                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10532                    + " package " + pkg.packageName
10533                    + " volume from " + pkgSetting.volumeUuid
10534                    + " to " + volumeUuid);
10535            pkgSetting.volumeUuid = volumeUuid;
10536        }
10537
10538        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10539    }
10540
10541    /**
10542     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10543     */
10544    private static boolean apkHasCode(String fileName) {
10545        StrictJarFile jarFile = null;
10546        try {
10547            jarFile = new StrictJarFile(fileName,
10548                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10549            return jarFile.findEntry("classes.dex") != null;
10550        } catch (IOException ignore) {
10551        } finally {
10552            try {
10553                if (jarFile != null) {
10554                    jarFile.close();
10555                }
10556            } catch (IOException ignore) {}
10557        }
10558        return false;
10559    }
10560
10561    /**
10562     * Enforces code policy for the package. This ensures that if an APK has
10563     * declared hasCode="true" in its manifest that the APK actually contains
10564     * code.
10565     *
10566     * @throws PackageManagerException If bytecode could not be found when it should exist
10567     */
10568    private static void assertCodePolicy(PackageParser.Package pkg)
10569            throws PackageManagerException {
10570        final boolean shouldHaveCode =
10571                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10572        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10573            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10574                    "Package " + pkg.baseCodePath + " code is missing");
10575        }
10576
10577        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10578            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10579                final boolean splitShouldHaveCode =
10580                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10581                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10582                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10583                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10584                }
10585            }
10586        }
10587    }
10588
10589    /**
10590     * Applies policy to the parsed package based upon the given policy flags.
10591     * Ensures the package is in a good state.
10592     * <p>
10593     * Implementation detail: This method must NOT have any side effect. It would
10594     * ideally be static, but, it requires locks to read system state.
10595     */
10596    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10597            final @ScanFlags int scanFlags) {
10598        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10599            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10600            if (pkg.applicationInfo.isDirectBootAware()) {
10601                // we're direct boot aware; set for all components
10602                for (PackageParser.Service s : pkg.services) {
10603                    s.info.encryptionAware = s.info.directBootAware = true;
10604                }
10605                for (PackageParser.Provider p : pkg.providers) {
10606                    p.info.encryptionAware = p.info.directBootAware = true;
10607                }
10608                for (PackageParser.Activity a : pkg.activities) {
10609                    a.info.encryptionAware = a.info.directBootAware = true;
10610                }
10611                for (PackageParser.Activity r : pkg.receivers) {
10612                    r.info.encryptionAware = r.info.directBootAware = true;
10613                }
10614            }
10615            if (compressedFileExists(pkg.codePath)) {
10616                pkg.isStub = true;
10617            }
10618        } else {
10619            // non system apps can't be flagged as core
10620            pkg.coreApp = false;
10621            // clear flags not applicable to regular apps
10622            pkg.applicationInfo.flags &=
10623                    ~ApplicationInfo.FLAG_PERSISTENT;
10624            pkg.applicationInfo.privateFlags &=
10625                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10626            pkg.applicationInfo.privateFlags &=
10627                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10628            // clear protected broadcasts
10629            pkg.protectedBroadcasts = null;
10630            // cap permission priorities
10631            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10632                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10633                    pkg.permissionGroups.get(i).info.priority = 0;
10634                }
10635            }
10636        }
10637        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10638            // ignore export request for single user receivers
10639            if (pkg.receivers != null) {
10640                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10641                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10642                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10643                        receiver.info.exported = false;
10644                    }
10645                }
10646            }
10647            // ignore export request for single user services
10648            if (pkg.services != null) {
10649                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10650                    final PackageParser.Service service = pkg.services.get(i);
10651                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10652                        service.info.exported = false;
10653                    }
10654                }
10655            }
10656            // ignore export request for single user providers
10657            if (pkg.providers != null) {
10658                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10659                    final PackageParser.Provider provider = pkg.providers.get(i);
10660                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10661                        provider.info.exported = false;
10662                    }
10663                }
10664            }
10665        }
10666
10667        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10668            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10669        }
10670
10671        if ((scanFlags & SCAN_AS_OEM) != 0) {
10672            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10673        }
10674
10675        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10676            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10677        }
10678
10679        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10680            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10681        }
10682
10683        if (!isSystemApp(pkg)) {
10684            // Only system apps can use these features.
10685            pkg.mOriginalPackages = null;
10686            pkg.mRealPackage = null;
10687            pkg.mAdoptPermissions = null;
10688        }
10689    }
10690
10691    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10692            throws PackageManagerException {
10693        if (object == null) {
10694            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10695        }
10696        return object;
10697    }
10698
10699    /**
10700     * Asserts the parsed package is valid according to the given policy. If the
10701     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10702     * <p>
10703     * Implementation detail: This method must NOT have any side effects. It would
10704     * ideally be static, but, it requires locks to read system state.
10705     *
10706     * @throws PackageManagerException If the package fails any of the validation checks
10707     */
10708    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10709            final @ScanFlags int scanFlags)
10710                    throws PackageManagerException {
10711        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10712            assertCodePolicy(pkg);
10713        }
10714
10715        if (pkg.applicationInfo.getCodePath() == null ||
10716                pkg.applicationInfo.getResourcePath() == null) {
10717            // Bail out. The resource and code paths haven't been set.
10718            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10719                    "Code and resource paths haven't been set correctly");
10720        }
10721
10722        // Make sure we're not adding any bogus keyset info
10723        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10724        ksms.assertScannedPackageValid(pkg);
10725
10726        synchronized (mPackages) {
10727            // The special "android" package can only be defined once
10728            if (pkg.packageName.equals("android")) {
10729                if (mAndroidApplication != null) {
10730                    Slog.w(TAG, "*************************************************");
10731                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10732                    Slog.w(TAG, " codePath=" + pkg.codePath);
10733                    Slog.w(TAG, "*************************************************");
10734                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10735                            "Core android package being redefined.  Skipping.");
10736                }
10737            }
10738
10739            // A package name must be unique; don't allow duplicates
10740            if (mPackages.containsKey(pkg.packageName)) {
10741                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10742                        "Application package " + pkg.packageName
10743                        + " already installed.  Skipping duplicate.");
10744            }
10745
10746            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10747                // Static libs have a synthetic package name containing the version
10748                // but we still want the base name to be unique.
10749                if (mPackages.containsKey(pkg.manifestPackageName)) {
10750                    throw new PackageManagerException(
10751                            "Duplicate static shared lib provider package");
10752                }
10753
10754                // Static shared libraries should have at least O target SDK
10755                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10756                    throw new PackageManagerException(
10757                            "Packages declaring static-shared libs must target O SDK or higher");
10758                }
10759
10760                // Package declaring static a shared lib cannot be instant apps
10761                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10762                    throw new PackageManagerException(
10763                            "Packages declaring static-shared libs cannot be instant apps");
10764                }
10765
10766                // Package declaring static a shared lib cannot be renamed since the package
10767                // name is synthetic and apps can't code around package manager internals.
10768                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10769                    throw new PackageManagerException(
10770                            "Packages declaring static-shared libs cannot be renamed");
10771                }
10772
10773                // Package declaring static a shared lib cannot declare child packages
10774                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10775                    throw new PackageManagerException(
10776                            "Packages declaring static-shared libs cannot have child packages");
10777                }
10778
10779                // Package declaring static a shared lib cannot declare dynamic libs
10780                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10781                    throw new PackageManagerException(
10782                            "Packages declaring static-shared libs cannot declare dynamic libs");
10783                }
10784
10785                // Package declaring static a shared lib cannot declare shared users
10786                if (pkg.mSharedUserId != null) {
10787                    throw new PackageManagerException(
10788                            "Packages declaring static-shared libs cannot declare shared users");
10789                }
10790
10791                // Static shared libs cannot declare activities
10792                if (!pkg.activities.isEmpty()) {
10793                    throw new PackageManagerException(
10794                            "Static shared libs cannot declare activities");
10795                }
10796
10797                // Static shared libs cannot declare services
10798                if (!pkg.services.isEmpty()) {
10799                    throw new PackageManagerException(
10800                            "Static shared libs cannot declare services");
10801                }
10802
10803                // Static shared libs cannot declare providers
10804                if (!pkg.providers.isEmpty()) {
10805                    throw new PackageManagerException(
10806                            "Static shared libs cannot declare content providers");
10807                }
10808
10809                // Static shared libs cannot declare receivers
10810                if (!pkg.receivers.isEmpty()) {
10811                    throw new PackageManagerException(
10812                            "Static shared libs cannot declare broadcast receivers");
10813                }
10814
10815                // Static shared libs cannot declare permission groups
10816                if (!pkg.permissionGroups.isEmpty()) {
10817                    throw new PackageManagerException(
10818                            "Static shared libs cannot declare permission groups");
10819                }
10820
10821                // Static shared libs cannot declare permissions
10822                if (!pkg.permissions.isEmpty()) {
10823                    throw new PackageManagerException(
10824                            "Static shared libs cannot declare permissions");
10825                }
10826
10827                // Static shared libs cannot declare protected broadcasts
10828                if (pkg.protectedBroadcasts != null) {
10829                    throw new PackageManagerException(
10830                            "Static shared libs cannot declare protected broadcasts");
10831                }
10832
10833                // Static shared libs cannot be overlay targets
10834                if (pkg.mOverlayTarget != null) {
10835                    throw new PackageManagerException(
10836                            "Static shared libs cannot be overlay targets");
10837                }
10838
10839                // The version codes must be ordered as lib versions
10840                long minVersionCode = Long.MIN_VALUE;
10841                long maxVersionCode = Long.MAX_VALUE;
10842
10843                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10844                        pkg.staticSharedLibName);
10845                if (versionedLib != null) {
10846                    final int versionCount = versionedLib.size();
10847                    for (int i = 0; i < versionCount; i++) {
10848                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10849                        final long libVersionCode = libInfo.getDeclaringPackage()
10850                                .getLongVersionCode();
10851                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10852                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10853                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10854                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10855                        } else {
10856                            minVersionCode = maxVersionCode = libVersionCode;
10857                            break;
10858                        }
10859                    }
10860                }
10861                if (pkg.getLongVersionCode() < minVersionCode
10862                        || pkg.getLongVersionCode() > maxVersionCode) {
10863                    throw new PackageManagerException("Static shared"
10864                            + " lib version codes must be ordered as lib versions");
10865                }
10866            }
10867
10868            // Only privileged apps and updated privileged apps can add child packages.
10869            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10870                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10871                    throw new PackageManagerException("Only privileged apps can add child "
10872                            + "packages. Ignoring package " + pkg.packageName);
10873                }
10874                final int childCount = pkg.childPackages.size();
10875                for (int i = 0; i < childCount; i++) {
10876                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10877                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10878                            childPkg.packageName)) {
10879                        throw new PackageManagerException("Can't override child of "
10880                                + "another disabled app. Ignoring package " + pkg.packageName);
10881                    }
10882                }
10883            }
10884
10885            // If we're only installing presumed-existing packages, require that the
10886            // scanned APK is both already known and at the path previously established
10887            // for it.  Previously unknown packages we pick up normally, but if we have an
10888            // a priori expectation about this package's install presence, enforce it.
10889            // With a singular exception for new system packages. When an OTA contains
10890            // a new system package, we allow the codepath to change from a system location
10891            // to the user-installed location. If we don't allow this change, any newer,
10892            // user-installed version of the application will be ignored.
10893            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10894                if (mExpectingBetter.containsKey(pkg.packageName)) {
10895                    logCriticalInfo(Log.WARN,
10896                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10897                } else {
10898                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10899                    if (known != null) {
10900                        if (DEBUG_PACKAGE_SCANNING) {
10901                            Log.d(TAG, "Examining " + pkg.codePath
10902                                    + " and requiring known paths " + known.codePathString
10903                                    + " & " + known.resourcePathString);
10904                        }
10905                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10906                                || !pkg.applicationInfo.getResourcePath().equals(
10907                                        known.resourcePathString)) {
10908                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10909                                    "Application package " + pkg.packageName
10910                                    + " found at " + pkg.applicationInfo.getCodePath()
10911                                    + " but expected at " + known.codePathString
10912                                    + "; ignoring.");
10913                        }
10914                    } else {
10915                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10916                                "Application package " + pkg.packageName
10917                                + " not found; ignoring.");
10918                    }
10919                }
10920            }
10921
10922            // Verify that this new package doesn't have any content providers
10923            // that conflict with existing packages.  Only do this if the
10924            // package isn't already installed, since we don't want to break
10925            // things that are installed.
10926            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10927                final int N = pkg.providers.size();
10928                int i;
10929                for (i=0; i<N; i++) {
10930                    PackageParser.Provider p = pkg.providers.get(i);
10931                    if (p.info.authority != null) {
10932                        String names[] = p.info.authority.split(";");
10933                        for (int j = 0; j < names.length; j++) {
10934                            if (mProvidersByAuthority.containsKey(names[j])) {
10935                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10936                                final String otherPackageName =
10937                                        ((other != null && other.getComponentName() != null) ?
10938                                                other.getComponentName().getPackageName() : "?");
10939                                throw new PackageManagerException(
10940                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10941                                        "Can't install because provider name " + names[j]
10942                                                + " (in package " + pkg.applicationInfo.packageName
10943                                                + ") is already used by " + otherPackageName);
10944                            }
10945                        }
10946                    }
10947                }
10948            }
10949
10950            // Verify that packages sharing a user with a privileged app are marked as privileged.
10951            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
10952                SharedUserSetting sharedUserSetting = null;
10953                try {
10954                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
10955                } catch (PackageManagerException ignore) {}
10956                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10957                    // Exempt SharedUsers signed with the platform key.
10958                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10959                    if ((platformPkgSetting.signatures.mSigningDetails
10960                            != PackageParser.SigningDetails.UNKNOWN)
10961                            && (compareSignatures(
10962                                    platformPkgSetting.signatures.mSigningDetails.signatures,
10963                                    pkg.mSigningDetails.signatures)
10964                                            != PackageManager.SIGNATURE_MATCH)) {
10965                        throw new PackageManagerException("Apps that share a user with a " +
10966                                "privileged app must themselves be marked as privileged. " +
10967                                pkg.packageName + " shares privileged user " +
10968                                pkg.mSharedUserId + ".");
10969                    }
10970                }
10971            }
10972
10973            // Apply policies specific for runtime resource overlays (RROs).
10974            if (pkg.mOverlayTarget != null) {
10975                // System overlays have some restrictions on their use of the 'static' state.
10976                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10977                    // We are scanning a system overlay. This can be the first scan of the
10978                    // system/vendor/oem partition, or an update to the system overlay.
10979                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10980                        // This must be an update to a system overlay.
10981                        final PackageSetting previousPkg = assertNotNull(
10982                                mSettings.getPackageLPr(pkg.packageName),
10983                                "previous package state not present");
10984
10985                        // Static overlays cannot be updated.
10986                        if (previousPkg.pkg.mOverlayIsStatic) {
10987                            throw new PackageManagerException("Overlay " + pkg.packageName +
10988                                    " is static and cannot be upgraded.");
10989                        // Non-static overlays cannot be converted to static overlays.
10990                        } else if (pkg.mOverlayIsStatic) {
10991                            throw new PackageManagerException("Overlay " + pkg.packageName +
10992                                    " cannot be upgraded into a static overlay.");
10993                        }
10994                    }
10995                } else {
10996                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
10997                    if (pkg.mOverlayIsStatic) {
10998                        throw new PackageManagerException("Overlay " + pkg.packageName +
10999                                " is static but not pre-installed.");
11000                    }
11001
11002                    // The only case where we allow installation of a non-system overlay is when
11003                    // its signature is signed with the platform certificate.
11004                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11005                    if ((platformPkgSetting.signatures.mSigningDetails
11006                            != PackageParser.SigningDetails.UNKNOWN)
11007                            && (compareSignatures(
11008                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11009                                    pkg.mSigningDetails.signatures)
11010                                            != PackageManager.SIGNATURE_MATCH)) {
11011                        throw new PackageManagerException("Overlay " + pkg.packageName +
11012                                " must be signed with the platform certificate.");
11013                    }
11014                }
11015            }
11016        }
11017    }
11018
11019    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11020            int type, String declaringPackageName, long declaringVersionCode) {
11021        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11022        if (versionedLib == null) {
11023            versionedLib = new LongSparseArray<>();
11024            mSharedLibraries.put(name, versionedLib);
11025            if (type == SharedLibraryInfo.TYPE_STATIC) {
11026                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11027            }
11028        } else if (versionedLib.indexOfKey(version) >= 0) {
11029            return false;
11030        }
11031        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11032                version, type, declaringPackageName, declaringVersionCode);
11033        versionedLib.put(version, libEntry);
11034        return true;
11035    }
11036
11037    private boolean removeSharedLibraryLPw(String name, long version) {
11038        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11039        if (versionedLib == null) {
11040            return false;
11041        }
11042        final int libIdx = versionedLib.indexOfKey(version);
11043        if (libIdx < 0) {
11044            return false;
11045        }
11046        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11047        versionedLib.remove(version);
11048        if (versionedLib.size() <= 0) {
11049            mSharedLibraries.remove(name);
11050            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11051                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11052                        .getPackageName());
11053            }
11054        }
11055        return true;
11056    }
11057
11058    /**
11059     * Adds a scanned package to the system. When this method is finished, the package will
11060     * be available for query, resolution, etc...
11061     */
11062    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11063            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11064        final String pkgName = pkg.packageName;
11065        if (mCustomResolverComponentName != null &&
11066                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11067            setUpCustomResolverActivity(pkg);
11068        }
11069
11070        if (pkg.packageName.equals("android")) {
11071            synchronized (mPackages) {
11072                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11073                    // Set up information for our fall-back user intent resolution activity.
11074                    mPlatformPackage = pkg;
11075                    pkg.mVersionCode = mSdkVersion;
11076                    pkg.mVersionCodeMajor = 0;
11077                    mAndroidApplication = pkg.applicationInfo;
11078                    if (!mResolverReplaced) {
11079                        mResolveActivity.applicationInfo = mAndroidApplication;
11080                        mResolveActivity.name = ResolverActivity.class.getName();
11081                        mResolveActivity.packageName = mAndroidApplication.packageName;
11082                        mResolveActivity.processName = "system:ui";
11083                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11084                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11085                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11086                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11087                        mResolveActivity.exported = true;
11088                        mResolveActivity.enabled = true;
11089                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11090                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11091                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11092                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11093                                | ActivityInfo.CONFIG_ORIENTATION
11094                                | ActivityInfo.CONFIG_KEYBOARD
11095                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11096                        mResolveInfo.activityInfo = mResolveActivity;
11097                        mResolveInfo.priority = 0;
11098                        mResolveInfo.preferredOrder = 0;
11099                        mResolveInfo.match = 0;
11100                        mResolveComponentName = new ComponentName(
11101                                mAndroidApplication.packageName, mResolveActivity.name);
11102                    }
11103                }
11104            }
11105        }
11106
11107        ArrayList<PackageParser.Package> clientLibPkgs = null;
11108        // writer
11109        synchronized (mPackages) {
11110            boolean hasStaticSharedLibs = false;
11111
11112            // Any app can add new static shared libraries
11113            if (pkg.staticSharedLibName != null) {
11114                // Static shared libs don't allow renaming as they have synthetic package
11115                // names to allow install of multiple versions, so use name from manifest.
11116                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11117                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11118                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11119                    hasStaticSharedLibs = true;
11120                } else {
11121                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11122                                + pkg.staticSharedLibName + " already exists; skipping");
11123                }
11124                // Static shared libs cannot be updated once installed since they
11125                // use synthetic package name which includes the version code, so
11126                // not need to update other packages's shared lib dependencies.
11127            }
11128
11129            if (!hasStaticSharedLibs
11130                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11131                // Only system apps can add new dynamic shared libraries.
11132                if (pkg.libraryNames != null) {
11133                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11134                        String name = pkg.libraryNames.get(i);
11135                        boolean allowed = false;
11136                        if (pkg.isUpdatedSystemApp()) {
11137                            // New library entries can only be added through the
11138                            // system image.  This is important to get rid of a lot
11139                            // of nasty edge cases: for example if we allowed a non-
11140                            // system update of the app to add a library, then uninstalling
11141                            // the update would make the library go away, and assumptions
11142                            // we made such as through app install filtering would now
11143                            // have allowed apps on the device which aren't compatible
11144                            // with it.  Better to just have the restriction here, be
11145                            // conservative, and create many fewer cases that can negatively
11146                            // impact the user experience.
11147                            final PackageSetting sysPs = mSettings
11148                                    .getDisabledSystemPkgLPr(pkg.packageName);
11149                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11150                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11151                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11152                                        allowed = true;
11153                                        break;
11154                                    }
11155                                }
11156                            }
11157                        } else {
11158                            allowed = true;
11159                        }
11160                        if (allowed) {
11161                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11162                                    SharedLibraryInfo.VERSION_UNDEFINED,
11163                                    SharedLibraryInfo.TYPE_DYNAMIC,
11164                                    pkg.packageName, pkg.getLongVersionCode())) {
11165                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11166                                        + name + " already exists; skipping");
11167                            }
11168                        } else {
11169                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11170                                    + name + " that is not declared on system image; skipping");
11171                        }
11172                    }
11173
11174                    if ((scanFlags & SCAN_BOOTING) == 0) {
11175                        // If we are not booting, we need to update any applications
11176                        // that are clients of our shared library.  If we are booting,
11177                        // this will all be done once the scan is complete.
11178                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11179                    }
11180                }
11181            }
11182        }
11183
11184        if ((scanFlags & SCAN_BOOTING) != 0) {
11185            // No apps can run during boot scan, so they don't need to be frozen
11186        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11187            // Caller asked to not kill app, so it's probably not frozen
11188        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11189            // Caller asked us to ignore frozen check for some reason; they
11190            // probably didn't know the package name
11191        } else {
11192            // We're doing major surgery on this package, so it better be frozen
11193            // right now to keep it from launching
11194            checkPackageFrozen(pkgName);
11195        }
11196
11197        // Also need to kill any apps that are dependent on the library.
11198        if (clientLibPkgs != null) {
11199            for (int i=0; i<clientLibPkgs.size(); i++) {
11200                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11201                killApplication(clientPkg.applicationInfo.packageName,
11202                        clientPkg.applicationInfo.uid, "update lib");
11203            }
11204        }
11205
11206        // writer
11207        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11208
11209        synchronized (mPackages) {
11210            // We don't expect installation to fail beyond this point
11211
11212            // Add the new setting to mSettings
11213            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11214            // Add the new setting to mPackages
11215            mPackages.put(pkg.applicationInfo.packageName, pkg);
11216            // Make sure we don't accidentally delete its data.
11217            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11218            while (iter.hasNext()) {
11219                PackageCleanItem item = iter.next();
11220                if (pkgName.equals(item.packageName)) {
11221                    iter.remove();
11222                }
11223            }
11224
11225            // Add the package's KeySets to the global KeySetManagerService
11226            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11227            ksms.addScannedPackageLPw(pkg);
11228
11229            int N = pkg.providers.size();
11230            StringBuilder r = null;
11231            int i;
11232            for (i=0; i<N; i++) {
11233                PackageParser.Provider p = pkg.providers.get(i);
11234                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11235                        p.info.processName);
11236                mProviders.addProvider(p);
11237                p.syncable = p.info.isSyncable;
11238                if (p.info.authority != null) {
11239                    String names[] = p.info.authority.split(";");
11240                    p.info.authority = null;
11241                    for (int j = 0; j < names.length; j++) {
11242                        if (j == 1 && p.syncable) {
11243                            // We only want the first authority for a provider to possibly be
11244                            // syncable, so if we already added this provider using a different
11245                            // authority clear the syncable flag. We copy the provider before
11246                            // changing it because the mProviders object contains a reference
11247                            // to a provider that we don't want to change.
11248                            // Only do this for the second authority since the resulting provider
11249                            // object can be the same for all future authorities for this provider.
11250                            p = new PackageParser.Provider(p);
11251                            p.syncable = false;
11252                        }
11253                        if (!mProvidersByAuthority.containsKey(names[j])) {
11254                            mProvidersByAuthority.put(names[j], p);
11255                            if (p.info.authority == null) {
11256                                p.info.authority = names[j];
11257                            } else {
11258                                p.info.authority = p.info.authority + ";" + names[j];
11259                            }
11260                            if (DEBUG_PACKAGE_SCANNING) {
11261                                if (chatty)
11262                                    Log.d(TAG, "Registered content provider: " + names[j]
11263                                            + ", className = " + p.info.name + ", isSyncable = "
11264                                            + p.info.isSyncable);
11265                            }
11266                        } else {
11267                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11268                            Slog.w(TAG, "Skipping provider name " + names[j] +
11269                                    " (in package " + pkg.applicationInfo.packageName +
11270                                    "): name already used by "
11271                                    + ((other != null && other.getComponentName() != null)
11272                                            ? other.getComponentName().getPackageName() : "?"));
11273                        }
11274                    }
11275                }
11276                if (chatty) {
11277                    if (r == null) {
11278                        r = new StringBuilder(256);
11279                    } else {
11280                        r.append(' ');
11281                    }
11282                    r.append(p.info.name);
11283                }
11284            }
11285            if (r != null) {
11286                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11287            }
11288
11289            N = pkg.services.size();
11290            r = null;
11291            for (i=0; i<N; i++) {
11292                PackageParser.Service s = pkg.services.get(i);
11293                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11294                        s.info.processName);
11295                mServices.addService(s);
11296                if (chatty) {
11297                    if (r == null) {
11298                        r = new StringBuilder(256);
11299                    } else {
11300                        r.append(' ');
11301                    }
11302                    r.append(s.info.name);
11303                }
11304            }
11305            if (r != null) {
11306                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11307            }
11308
11309            N = pkg.receivers.size();
11310            r = null;
11311            for (i=0; i<N; i++) {
11312                PackageParser.Activity a = pkg.receivers.get(i);
11313                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11314                        a.info.processName);
11315                mReceivers.addActivity(a, "receiver");
11316                if (chatty) {
11317                    if (r == null) {
11318                        r = new StringBuilder(256);
11319                    } else {
11320                        r.append(' ');
11321                    }
11322                    r.append(a.info.name);
11323                }
11324            }
11325            if (r != null) {
11326                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11327            }
11328
11329            N = pkg.activities.size();
11330            r = null;
11331            for (i=0; i<N; i++) {
11332                PackageParser.Activity a = pkg.activities.get(i);
11333                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11334                        a.info.processName);
11335                mActivities.addActivity(a, "activity");
11336                if (chatty) {
11337                    if (r == null) {
11338                        r = new StringBuilder(256);
11339                    } else {
11340                        r.append(' ');
11341                    }
11342                    r.append(a.info.name);
11343                }
11344            }
11345            if (r != null) {
11346                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11347            }
11348
11349            // Don't allow ephemeral applications to define new permissions groups.
11350            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11351                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11352                        + " ignored: instant apps cannot define new permission groups.");
11353            } else {
11354                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11355            }
11356
11357            // Don't allow ephemeral applications to define new permissions.
11358            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11359                Slog.w(TAG, "Permissions from package " + pkg.packageName
11360                        + " ignored: instant apps cannot define new permissions.");
11361            } else {
11362                mPermissionManager.addAllPermissions(pkg, chatty);
11363            }
11364
11365            N = pkg.instrumentation.size();
11366            r = null;
11367            for (i=0; i<N; i++) {
11368                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11369                a.info.packageName = pkg.applicationInfo.packageName;
11370                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11371                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11372                a.info.splitNames = pkg.splitNames;
11373                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11374                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11375                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11376                a.info.dataDir = pkg.applicationInfo.dataDir;
11377                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11378                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11379                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11380                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11381                mInstrumentation.put(a.getComponentName(), a);
11382                if (chatty) {
11383                    if (r == null) {
11384                        r = new StringBuilder(256);
11385                    } else {
11386                        r.append(' ');
11387                    }
11388                    r.append(a.info.name);
11389                }
11390            }
11391            if (r != null) {
11392                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11393            }
11394
11395            if (pkg.protectedBroadcasts != null) {
11396                N = pkg.protectedBroadcasts.size();
11397                synchronized (mProtectedBroadcasts) {
11398                    for (i = 0; i < N; i++) {
11399                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11400                    }
11401                }
11402            }
11403        }
11404
11405        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11406    }
11407
11408    /**
11409     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11410     * is derived purely on the basis of the contents of {@code scanFile} and
11411     * {@code cpuAbiOverride}.
11412     *
11413     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11414     */
11415    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11416            boolean extractLibs)
11417                    throws PackageManagerException {
11418        // Give ourselves some initial paths; we'll come back for another
11419        // pass once we've determined ABI below.
11420        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11421
11422        // We would never need to extract libs for forward-locked and external packages,
11423        // since the container service will do it for us. We shouldn't attempt to
11424        // extract libs from system app when it was not updated.
11425        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11426                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11427            extractLibs = false;
11428        }
11429
11430        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11431        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11432
11433        NativeLibraryHelper.Handle handle = null;
11434        try {
11435            handle = NativeLibraryHelper.Handle.create(pkg);
11436            // TODO(multiArch): This can be null for apps that didn't go through the
11437            // usual installation process. We can calculate it again, like we
11438            // do during install time.
11439            //
11440            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11441            // unnecessary.
11442            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11443
11444            // Null out the abis so that they can be recalculated.
11445            pkg.applicationInfo.primaryCpuAbi = null;
11446            pkg.applicationInfo.secondaryCpuAbi = null;
11447            if (isMultiArch(pkg.applicationInfo)) {
11448                // Warn if we've set an abiOverride for multi-lib packages..
11449                // By definition, we need to copy both 32 and 64 bit libraries for
11450                // such packages.
11451                if (pkg.cpuAbiOverride != null
11452                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11453                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11454                }
11455
11456                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11457                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11458                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11459                    if (extractLibs) {
11460                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11461                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11462                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11463                                useIsaSpecificSubdirs);
11464                    } else {
11465                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11466                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11467                    }
11468                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11469                }
11470
11471                // Shared library native code should be in the APK zip aligned
11472                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11473                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11474                            "Shared library native lib extraction not supported");
11475                }
11476
11477                maybeThrowExceptionForMultiArchCopy(
11478                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11479
11480                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11481                    if (extractLibs) {
11482                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11483                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11484                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11485                                useIsaSpecificSubdirs);
11486                    } else {
11487                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11488                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11489                    }
11490                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11491                }
11492
11493                maybeThrowExceptionForMultiArchCopy(
11494                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11495
11496                if (abi64 >= 0) {
11497                    // Shared library native libs should be in the APK zip aligned
11498                    if (extractLibs && pkg.isLibrary()) {
11499                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11500                                "Shared library native lib extraction not supported");
11501                    }
11502                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11503                }
11504
11505                if (abi32 >= 0) {
11506                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11507                    if (abi64 >= 0) {
11508                        if (pkg.use32bitAbi) {
11509                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11510                            pkg.applicationInfo.primaryCpuAbi = abi;
11511                        } else {
11512                            pkg.applicationInfo.secondaryCpuAbi = abi;
11513                        }
11514                    } else {
11515                        pkg.applicationInfo.primaryCpuAbi = abi;
11516                    }
11517                }
11518            } else {
11519                String[] abiList = (cpuAbiOverride != null) ?
11520                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11521
11522                // Enable gross and lame hacks for apps that are built with old
11523                // SDK tools. We must scan their APKs for renderscript bitcode and
11524                // not launch them if it's present. Don't bother checking on devices
11525                // that don't have 64 bit support.
11526                boolean needsRenderScriptOverride = false;
11527                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11528                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11529                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11530                    needsRenderScriptOverride = true;
11531                }
11532
11533                final int copyRet;
11534                if (extractLibs) {
11535                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11536                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11537                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11538                } else {
11539                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11540                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11541                }
11542                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11543
11544                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11545                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11546                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11547                }
11548
11549                if (copyRet >= 0) {
11550                    // Shared libraries that have native libs must be multi-architecture
11551                    if (pkg.isLibrary()) {
11552                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11553                                "Shared library with native libs must be multiarch");
11554                    }
11555                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11556                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11557                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11558                } else if (needsRenderScriptOverride) {
11559                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11560                }
11561            }
11562        } catch (IOException ioe) {
11563            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11564        } finally {
11565            IoUtils.closeQuietly(handle);
11566        }
11567
11568        // Now that we've calculated the ABIs and determined if it's an internal app,
11569        // we will go ahead and populate the nativeLibraryPath.
11570        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11571    }
11572
11573    /**
11574     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11575     * i.e, so that all packages can be run inside a single process if required.
11576     *
11577     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11578     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11579     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11580     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11581     * updating a package that belongs to a shared user.
11582     *
11583     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11584     * adds unnecessary complexity.
11585     */
11586    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11587            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11588        List<String> changedAbiCodePath = null;
11589        String requiredInstructionSet = null;
11590        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11591            requiredInstructionSet = VMRuntime.getInstructionSet(
11592                     scannedPackage.applicationInfo.primaryCpuAbi);
11593        }
11594
11595        PackageSetting requirer = null;
11596        for (PackageSetting ps : packagesForUser) {
11597            // If packagesForUser contains scannedPackage, we skip it. This will happen
11598            // when scannedPackage is an update of an existing package. Without this check,
11599            // we will never be able to change the ABI of any package belonging to a shared
11600            // user, even if it's compatible with other packages.
11601            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11602                if (ps.primaryCpuAbiString == null) {
11603                    continue;
11604                }
11605
11606                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11607                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11608                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11609                    // this but there's not much we can do.
11610                    String errorMessage = "Instruction set mismatch, "
11611                            + ((requirer == null) ? "[caller]" : requirer)
11612                            + " requires " + requiredInstructionSet + " whereas " + ps
11613                            + " requires " + instructionSet;
11614                    Slog.w(TAG, errorMessage);
11615                }
11616
11617                if (requiredInstructionSet == null) {
11618                    requiredInstructionSet = instructionSet;
11619                    requirer = ps;
11620                }
11621            }
11622        }
11623
11624        if (requiredInstructionSet != null) {
11625            String adjustedAbi;
11626            if (requirer != null) {
11627                // requirer != null implies that either scannedPackage was null or that scannedPackage
11628                // did not require an ABI, in which case we have to adjust scannedPackage to match
11629                // the ABI of the set (which is the same as requirer's ABI)
11630                adjustedAbi = requirer.primaryCpuAbiString;
11631                if (scannedPackage != null) {
11632                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11633                }
11634            } else {
11635                // requirer == null implies that we're updating all ABIs in the set to
11636                // match scannedPackage.
11637                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11638            }
11639
11640            for (PackageSetting ps : packagesForUser) {
11641                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11642                    if (ps.primaryCpuAbiString != null) {
11643                        continue;
11644                    }
11645
11646                    ps.primaryCpuAbiString = adjustedAbi;
11647                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11648                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11649                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11650                        if (DEBUG_ABI_SELECTION) {
11651                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11652                                    + " (requirer="
11653                                    + (requirer != null ? requirer.pkg : "null")
11654                                    + ", scannedPackage="
11655                                    + (scannedPackage != null ? scannedPackage : "null")
11656                                    + ")");
11657                        }
11658                        if (changedAbiCodePath == null) {
11659                            changedAbiCodePath = new ArrayList<>();
11660                        }
11661                        changedAbiCodePath.add(ps.codePathString);
11662                    }
11663                }
11664            }
11665        }
11666        return changedAbiCodePath;
11667    }
11668
11669    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11670        synchronized (mPackages) {
11671            mResolverReplaced = true;
11672            // Set up information for custom user intent resolution activity.
11673            mResolveActivity.applicationInfo = pkg.applicationInfo;
11674            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11675            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11676            mResolveActivity.processName = pkg.applicationInfo.packageName;
11677            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11678            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11679                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11680            mResolveActivity.theme = 0;
11681            mResolveActivity.exported = true;
11682            mResolveActivity.enabled = true;
11683            mResolveInfo.activityInfo = mResolveActivity;
11684            mResolveInfo.priority = 0;
11685            mResolveInfo.preferredOrder = 0;
11686            mResolveInfo.match = 0;
11687            mResolveComponentName = mCustomResolverComponentName;
11688            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11689                    mResolveComponentName);
11690        }
11691    }
11692
11693    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11694        if (installerActivity == null) {
11695            if (DEBUG_INSTANT) {
11696                Slog.d(TAG, "Clear ephemeral installer activity");
11697            }
11698            mInstantAppInstallerActivity = null;
11699            return;
11700        }
11701
11702        if (DEBUG_INSTANT) {
11703            Slog.d(TAG, "Set ephemeral installer activity: "
11704                    + installerActivity.getComponentName());
11705        }
11706        // Set up information for ephemeral installer activity
11707        mInstantAppInstallerActivity = installerActivity;
11708        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11709                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11710        mInstantAppInstallerActivity.exported = true;
11711        mInstantAppInstallerActivity.enabled = true;
11712        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11713        mInstantAppInstallerInfo.priority = 1;
11714        mInstantAppInstallerInfo.preferredOrder = 1;
11715        mInstantAppInstallerInfo.isDefault = true;
11716        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11717                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11718    }
11719
11720    private static String calculateBundledApkRoot(final String codePathString) {
11721        final File codePath = new File(codePathString);
11722        final File codeRoot;
11723        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11724            codeRoot = Environment.getRootDirectory();
11725        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11726            codeRoot = Environment.getOemDirectory();
11727        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11728            codeRoot = Environment.getVendorDirectory();
11729        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11730            codeRoot = Environment.getProductDirectory();
11731        } else {
11732            // Unrecognized code path; take its top real segment as the apk root:
11733            // e.g. /something/app/blah.apk => /something
11734            try {
11735                File f = codePath.getCanonicalFile();
11736                File parent = f.getParentFile();    // non-null because codePath is a file
11737                File tmp;
11738                while ((tmp = parent.getParentFile()) != null) {
11739                    f = parent;
11740                    parent = tmp;
11741                }
11742                codeRoot = f;
11743                Slog.w(TAG, "Unrecognized code path "
11744                        + codePath + " - using " + codeRoot);
11745            } catch (IOException e) {
11746                // Can't canonicalize the code path -- shenanigans?
11747                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11748                return Environment.getRootDirectory().getPath();
11749            }
11750        }
11751        return codeRoot.getPath();
11752    }
11753
11754    /**
11755     * Derive and set the location of native libraries for the given package,
11756     * which varies depending on where and how the package was installed.
11757     */
11758    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11759        final ApplicationInfo info = pkg.applicationInfo;
11760        final String codePath = pkg.codePath;
11761        final File codeFile = new File(codePath);
11762        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11763        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11764
11765        info.nativeLibraryRootDir = null;
11766        info.nativeLibraryRootRequiresIsa = false;
11767        info.nativeLibraryDir = null;
11768        info.secondaryNativeLibraryDir = null;
11769
11770        if (isApkFile(codeFile)) {
11771            // Monolithic install
11772            if (bundledApp) {
11773                // If "/system/lib64/apkname" exists, assume that is the per-package
11774                // native library directory to use; otherwise use "/system/lib/apkname".
11775                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11776                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11777                        getPrimaryInstructionSet(info));
11778
11779                // This is a bundled system app so choose the path based on the ABI.
11780                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11781                // is just the default path.
11782                final String apkName = deriveCodePathName(codePath);
11783                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11784                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11785                        apkName).getAbsolutePath();
11786
11787                if (info.secondaryCpuAbi != null) {
11788                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11789                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11790                            secondaryLibDir, apkName).getAbsolutePath();
11791                }
11792            } else if (asecApp) {
11793                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11794                        .getAbsolutePath();
11795            } else {
11796                final String apkName = deriveCodePathName(codePath);
11797                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11798                        .getAbsolutePath();
11799            }
11800
11801            info.nativeLibraryRootRequiresIsa = false;
11802            info.nativeLibraryDir = info.nativeLibraryRootDir;
11803        } else {
11804            // Cluster install
11805            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11806            info.nativeLibraryRootRequiresIsa = true;
11807
11808            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11809                    getPrimaryInstructionSet(info)).getAbsolutePath();
11810
11811            if (info.secondaryCpuAbi != null) {
11812                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11813                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11814            }
11815        }
11816    }
11817
11818    /**
11819     * Calculate the abis and roots for a bundled app. These can uniquely
11820     * be determined from the contents of the system partition, i.e whether
11821     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11822     * of this information, and instead assume that the system was built
11823     * sensibly.
11824     */
11825    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11826                                           PackageSetting pkgSetting) {
11827        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11828
11829        // If "/system/lib64/apkname" exists, assume that is the per-package
11830        // native library directory to use; otherwise use "/system/lib/apkname".
11831        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11832        setBundledAppAbi(pkg, apkRoot, apkName);
11833        // pkgSetting might be null during rescan following uninstall of updates
11834        // to a bundled app, so accommodate that possibility.  The settings in
11835        // that case will be established later from the parsed package.
11836        //
11837        // If the settings aren't null, sync them up with what we've just derived.
11838        // note that apkRoot isn't stored in the package settings.
11839        if (pkgSetting != null) {
11840            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11841            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11842        }
11843    }
11844
11845    /**
11846     * Deduces the ABI of a bundled app and sets the relevant fields on the
11847     * parsed pkg object.
11848     *
11849     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11850     *        under which system libraries are installed.
11851     * @param apkName the name of the installed package.
11852     */
11853    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11854        final File codeFile = new File(pkg.codePath);
11855
11856        final boolean has64BitLibs;
11857        final boolean has32BitLibs;
11858        if (isApkFile(codeFile)) {
11859            // Monolithic install
11860            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11861            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11862        } else {
11863            // Cluster install
11864            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11865            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11866                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11867                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11868                has64BitLibs = (new File(rootDir, isa)).exists();
11869            } else {
11870                has64BitLibs = false;
11871            }
11872            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11873                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11874                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11875                has32BitLibs = (new File(rootDir, isa)).exists();
11876            } else {
11877                has32BitLibs = false;
11878            }
11879        }
11880
11881        if (has64BitLibs && !has32BitLibs) {
11882            // The package has 64 bit libs, but not 32 bit libs. Its primary
11883            // ABI should be 64 bit. We can safely assume here that the bundled
11884            // native libraries correspond to the most preferred ABI in the list.
11885
11886            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11887            pkg.applicationInfo.secondaryCpuAbi = null;
11888        } else if (has32BitLibs && !has64BitLibs) {
11889            // The package has 32 bit libs but not 64 bit libs. Its primary
11890            // ABI should be 32 bit.
11891
11892            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11893            pkg.applicationInfo.secondaryCpuAbi = null;
11894        } else if (has32BitLibs && has64BitLibs) {
11895            // The application has both 64 and 32 bit bundled libraries. We check
11896            // here that the app declares multiArch support, and warn if it doesn't.
11897            //
11898            // We will be lenient here and record both ABIs. The primary will be the
11899            // ABI that's higher on the list, i.e, a device that's configured to prefer
11900            // 64 bit apps will see a 64 bit primary ABI,
11901
11902            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11903                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11904            }
11905
11906            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11907                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11908                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11909            } else {
11910                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11911                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11912            }
11913        } else {
11914            pkg.applicationInfo.primaryCpuAbi = null;
11915            pkg.applicationInfo.secondaryCpuAbi = null;
11916        }
11917    }
11918
11919    private void killApplication(String pkgName, int appId, String reason) {
11920        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11921    }
11922
11923    private void killApplication(String pkgName, int appId, int userId, String reason) {
11924        // Request the ActivityManager to kill the process(only for existing packages)
11925        // so that we do not end up in a confused state while the user is still using the older
11926        // version of the application while the new one gets installed.
11927        final long token = Binder.clearCallingIdentity();
11928        try {
11929            IActivityManager am = ActivityManager.getService();
11930            if (am != null) {
11931                try {
11932                    am.killApplication(pkgName, appId, userId, reason);
11933                } catch (RemoteException e) {
11934                }
11935            }
11936        } finally {
11937            Binder.restoreCallingIdentity(token);
11938        }
11939    }
11940
11941    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11942        // Remove the parent package setting
11943        PackageSetting ps = (PackageSetting) pkg.mExtras;
11944        if (ps != null) {
11945            removePackageLI(ps, chatty);
11946        }
11947        // Remove the child package setting
11948        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11949        for (int i = 0; i < childCount; i++) {
11950            PackageParser.Package childPkg = pkg.childPackages.get(i);
11951            ps = (PackageSetting) childPkg.mExtras;
11952            if (ps != null) {
11953                removePackageLI(ps, chatty);
11954            }
11955        }
11956    }
11957
11958    void removePackageLI(PackageSetting ps, boolean chatty) {
11959        if (DEBUG_INSTALL) {
11960            if (chatty)
11961                Log.d(TAG, "Removing package " + ps.name);
11962        }
11963
11964        // writer
11965        synchronized (mPackages) {
11966            mPackages.remove(ps.name);
11967            final PackageParser.Package pkg = ps.pkg;
11968            if (pkg != null) {
11969                cleanPackageDataStructuresLILPw(pkg, chatty);
11970            }
11971        }
11972    }
11973
11974    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11975        if (DEBUG_INSTALL) {
11976            if (chatty)
11977                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11978        }
11979
11980        // writer
11981        synchronized (mPackages) {
11982            // Remove the parent package
11983            mPackages.remove(pkg.applicationInfo.packageName);
11984            cleanPackageDataStructuresLILPw(pkg, chatty);
11985
11986            // Remove the child packages
11987            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11988            for (int i = 0; i < childCount; i++) {
11989                PackageParser.Package childPkg = pkg.childPackages.get(i);
11990                mPackages.remove(childPkg.applicationInfo.packageName);
11991                cleanPackageDataStructuresLILPw(childPkg, chatty);
11992            }
11993        }
11994    }
11995
11996    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11997        int N = pkg.providers.size();
11998        StringBuilder r = null;
11999        int i;
12000        for (i=0; i<N; i++) {
12001            PackageParser.Provider p = pkg.providers.get(i);
12002            mProviders.removeProvider(p);
12003            if (p.info.authority == null) {
12004
12005                /* There was another ContentProvider with this authority when
12006                 * this app was installed so this authority is null,
12007                 * Ignore it as we don't have to unregister the provider.
12008                 */
12009                continue;
12010            }
12011            String names[] = p.info.authority.split(";");
12012            for (int j = 0; j < names.length; j++) {
12013                if (mProvidersByAuthority.get(names[j]) == p) {
12014                    mProvidersByAuthority.remove(names[j]);
12015                    if (DEBUG_REMOVE) {
12016                        if (chatty)
12017                            Log.d(TAG, "Unregistered content provider: " + names[j]
12018                                    + ", className = " + p.info.name + ", isSyncable = "
12019                                    + p.info.isSyncable);
12020                    }
12021                }
12022            }
12023            if (DEBUG_REMOVE && chatty) {
12024                if (r == null) {
12025                    r = new StringBuilder(256);
12026                } else {
12027                    r.append(' ');
12028                }
12029                r.append(p.info.name);
12030            }
12031        }
12032        if (r != null) {
12033            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12034        }
12035
12036        N = pkg.services.size();
12037        r = null;
12038        for (i=0; i<N; i++) {
12039            PackageParser.Service s = pkg.services.get(i);
12040            mServices.removeService(s);
12041            if (chatty) {
12042                if (r == null) {
12043                    r = new StringBuilder(256);
12044                } else {
12045                    r.append(' ');
12046                }
12047                r.append(s.info.name);
12048            }
12049        }
12050        if (r != null) {
12051            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12052        }
12053
12054        N = pkg.receivers.size();
12055        r = null;
12056        for (i=0; i<N; i++) {
12057            PackageParser.Activity a = pkg.receivers.get(i);
12058            mReceivers.removeActivity(a, "receiver");
12059            if (DEBUG_REMOVE && chatty) {
12060                if (r == null) {
12061                    r = new StringBuilder(256);
12062                } else {
12063                    r.append(' ');
12064                }
12065                r.append(a.info.name);
12066            }
12067        }
12068        if (r != null) {
12069            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12070        }
12071
12072        N = pkg.activities.size();
12073        r = null;
12074        for (i=0; i<N; i++) {
12075            PackageParser.Activity a = pkg.activities.get(i);
12076            mActivities.removeActivity(a, "activity");
12077            if (DEBUG_REMOVE && chatty) {
12078                if (r == null) {
12079                    r = new StringBuilder(256);
12080                } else {
12081                    r.append(' ');
12082                }
12083                r.append(a.info.name);
12084            }
12085        }
12086        if (r != null) {
12087            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12088        }
12089
12090        mPermissionManager.removeAllPermissions(pkg, chatty);
12091
12092        N = pkg.instrumentation.size();
12093        r = null;
12094        for (i=0; i<N; i++) {
12095            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12096            mInstrumentation.remove(a.getComponentName());
12097            if (DEBUG_REMOVE && chatty) {
12098                if (r == null) {
12099                    r = new StringBuilder(256);
12100                } else {
12101                    r.append(' ');
12102                }
12103                r.append(a.info.name);
12104            }
12105        }
12106        if (r != null) {
12107            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12108        }
12109
12110        r = null;
12111        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12112            // Only system apps can hold shared libraries.
12113            if (pkg.libraryNames != null) {
12114                for (i = 0; i < pkg.libraryNames.size(); i++) {
12115                    String name = pkg.libraryNames.get(i);
12116                    if (removeSharedLibraryLPw(name, 0)) {
12117                        if (DEBUG_REMOVE && chatty) {
12118                            if (r == null) {
12119                                r = new StringBuilder(256);
12120                            } else {
12121                                r.append(' ');
12122                            }
12123                            r.append(name);
12124                        }
12125                    }
12126                }
12127            }
12128        }
12129
12130        r = null;
12131
12132        // Any package can hold static shared libraries.
12133        if (pkg.staticSharedLibName != null) {
12134            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12135                if (DEBUG_REMOVE && chatty) {
12136                    if (r == null) {
12137                        r = new StringBuilder(256);
12138                    } else {
12139                        r.append(' ');
12140                    }
12141                    r.append(pkg.staticSharedLibName);
12142                }
12143            }
12144        }
12145
12146        if (r != null) {
12147            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12148        }
12149    }
12150
12151
12152    final class ActivityIntentResolver
12153            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12154        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12155                boolean defaultOnly, int userId) {
12156            if (!sUserManager.exists(userId)) return null;
12157            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12158            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12159        }
12160
12161        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12162                int userId) {
12163            if (!sUserManager.exists(userId)) return null;
12164            mFlags = flags;
12165            return super.queryIntent(intent, resolvedType,
12166                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12167                    userId);
12168        }
12169
12170        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12171                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12172            if (!sUserManager.exists(userId)) return null;
12173            if (packageActivities == null) {
12174                return null;
12175            }
12176            mFlags = flags;
12177            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12178            final int N = packageActivities.size();
12179            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12180                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12181
12182            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12183            for (int i = 0; i < N; ++i) {
12184                intentFilters = packageActivities.get(i).intents;
12185                if (intentFilters != null && intentFilters.size() > 0) {
12186                    PackageParser.ActivityIntentInfo[] array =
12187                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12188                    intentFilters.toArray(array);
12189                    listCut.add(array);
12190                }
12191            }
12192            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12193        }
12194
12195        /**
12196         * Finds a privileged activity that matches the specified activity names.
12197         */
12198        private PackageParser.Activity findMatchingActivity(
12199                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12200            for (PackageParser.Activity sysActivity : activityList) {
12201                if (sysActivity.info.name.equals(activityInfo.name)) {
12202                    return sysActivity;
12203                }
12204                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12205                    return sysActivity;
12206                }
12207                if (sysActivity.info.targetActivity != null) {
12208                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12209                        return sysActivity;
12210                    }
12211                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12212                        return sysActivity;
12213                    }
12214                }
12215            }
12216            return null;
12217        }
12218
12219        public class IterGenerator<E> {
12220            public Iterator<E> generate(ActivityIntentInfo info) {
12221                return null;
12222            }
12223        }
12224
12225        public class ActionIterGenerator extends IterGenerator<String> {
12226            @Override
12227            public Iterator<String> generate(ActivityIntentInfo info) {
12228                return info.actionsIterator();
12229            }
12230        }
12231
12232        public class CategoriesIterGenerator extends IterGenerator<String> {
12233            @Override
12234            public Iterator<String> generate(ActivityIntentInfo info) {
12235                return info.categoriesIterator();
12236            }
12237        }
12238
12239        public class SchemesIterGenerator extends IterGenerator<String> {
12240            @Override
12241            public Iterator<String> generate(ActivityIntentInfo info) {
12242                return info.schemesIterator();
12243            }
12244        }
12245
12246        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12247            @Override
12248            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12249                return info.authoritiesIterator();
12250            }
12251        }
12252
12253        /**
12254         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12255         * MODIFIED. Do not pass in a list that should not be changed.
12256         */
12257        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12258                IterGenerator<T> generator, Iterator<T> searchIterator) {
12259            // loop through the set of actions; every one must be found in the intent filter
12260            while (searchIterator.hasNext()) {
12261                // we must have at least one filter in the list to consider a match
12262                if (intentList.size() == 0) {
12263                    break;
12264                }
12265
12266                final T searchAction = searchIterator.next();
12267
12268                // loop through the set of intent filters
12269                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12270                while (intentIter.hasNext()) {
12271                    final ActivityIntentInfo intentInfo = intentIter.next();
12272                    boolean selectionFound = false;
12273
12274                    // loop through the intent filter's selection criteria; at least one
12275                    // of them must match the searched criteria
12276                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12277                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12278                        final T intentSelection = intentSelectionIter.next();
12279                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12280                            selectionFound = true;
12281                            break;
12282                        }
12283                    }
12284
12285                    // the selection criteria wasn't found in this filter's set; this filter
12286                    // is not a potential match
12287                    if (!selectionFound) {
12288                        intentIter.remove();
12289                    }
12290                }
12291            }
12292        }
12293
12294        private boolean isProtectedAction(ActivityIntentInfo filter) {
12295            final Iterator<String> actionsIter = filter.actionsIterator();
12296            while (actionsIter != null && actionsIter.hasNext()) {
12297                final String filterAction = actionsIter.next();
12298                if (PROTECTED_ACTIONS.contains(filterAction)) {
12299                    return true;
12300                }
12301            }
12302            return false;
12303        }
12304
12305        /**
12306         * Adjusts the priority of the given intent filter according to policy.
12307         * <p>
12308         * <ul>
12309         * <li>The priority for non privileged applications is capped to '0'</li>
12310         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12311         * <li>The priority for unbundled updates to privileged applications is capped to the
12312         *      priority defined on the system partition</li>
12313         * </ul>
12314         * <p>
12315         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12316         * allowed to obtain any priority on any action.
12317         */
12318        private void adjustPriority(
12319                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12320            // nothing to do; priority is fine as-is
12321            if (intent.getPriority() <= 0) {
12322                return;
12323            }
12324
12325            final ActivityInfo activityInfo = intent.activity.info;
12326            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12327
12328            final boolean privilegedApp =
12329                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12330            if (!privilegedApp) {
12331                // non-privileged applications can never define a priority >0
12332                if (DEBUG_FILTERS) {
12333                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12334                            + " package: " + applicationInfo.packageName
12335                            + " activity: " + intent.activity.className
12336                            + " origPrio: " + intent.getPriority());
12337                }
12338                intent.setPriority(0);
12339                return;
12340            }
12341
12342            if (systemActivities == null) {
12343                // the system package is not disabled; we're parsing the system partition
12344                if (isProtectedAction(intent)) {
12345                    if (mDeferProtectedFilters) {
12346                        // We can't deal with these just yet. No component should ever obtain a
12347                        // >0 priority for a protected actions, with ONE exception -- the setup
12348                        // wizard. The setup wizard, however, cannot be known until we're able to
12349                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12350                        // until all intent filters have been processed. Chicken, meet egg.
12351                        // Let the filter temporarily have a high priority and rectify the
12352                        // priorities after all system packages have been scanned.
12353                        mProtectedFilters.add(intent);
12354                        if (DEBUG_FILTERS) {
12355                            Slog.i(TAG, "Protected action; save for later;"
12356                                    + " package: " + applicationInfo.packageName
12357                                    + " activity: " + intent.activity.className
12358                                    + " origPrio: " + intent.getPriority());
12359                        }
12360                        return;
12361                    } else {
12362                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12363                            Slog.i(TAG, "No setup wizard;"
12364                                + " All protected intents capped to priority 0");
12365                        }
12366                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12367                            if (DEBUG_FILTERS) {
12368                                Slog.i(TAG, "Found setup wizard;"
12369                                    + " allow priority " + intent.getPriority() + ";"
12370                                    + " package: " + intent.activity.info.packageName
12371                                    + " activity: " + intent.activity.className
12372                                    + " priority: " + intent.getPriority());
12373                            }
12374                            // setup wizard gets whatever it wants
12375                            return;
12376                        }
12377                        if (DEBUG_FILTERS) {
12378                            Slog.i(TAG, "Protected action; cap priority to 0;"
12379                                    + " package: " + intent.activity.info.packageName
12380                                    + " activity: " + intent.activity.className
12381                                    + " origPrio: " + intent.getPriority());
12382                        }
12383                        intent.setPriority(0);
12384                        return;
12385                    }
12386                }
12387                // privileged apps on the system image get whatever priority they request
12388                return;
12389            }
12390
12391            // privileged app unbundled update ... try to find the same activity
12392            final PackageParser.Activity foundActivity =
12393                    findMatchingActivity(systemActivities, activityInfo);
12394            if (foundActivity == null) {
12395                // this is a new activity; it cannot obtain >0 priority
12396                if (DEBUG_FILTERS) {
12397                    Slog.i(TAG, "New activity; cap priority to 0;"
12398                            + " package: " + applicationInfo.packageName
12399                            + " activity: " + intent.activity.className
12400                            + " origPrio: " + intent.getPriority());
12401                }
12402                intent.setPriority(0);
12403                return;
12404            }
12405
12406            // found activity, now check for filter equivalence
12407
12408            // a shallow copy is enough; we modify the list, not its contents
12409            final List<ActivityIntentInfo> intentListCopy =
12410                    new ArrayList<>(foundActivity.intents);
12411            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12412
12413            // find matching action subsets
12414            final Iterator<String> actionsIterator = intent.actionsIterator();
12415            if (actionsIterator != null) {
12416                getIntentListSubset(
12417                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12418                if (intentListCopy.size() == 0) {
12419                    // no more intents to match; we're not equivalent
12420                    if (DEBUG_FILTERS) {
12421                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12422                                + " package: " + applicationInfo.packageName
12423                                + " activity: " + intent.activity.className
12424                                + " origPrio: " + intent.getPriority());
12425                    }
12426                    intent.setPriority(0);
12427                    return;
12428                }
12429            }
12430
12431            // find matching category subsets
12432            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12433            if (categoriesIterator != null) {
12434                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12435                        categoriesIterator);
12436                if (intentListCopy.size() == 0) {
12437                    // no more intents to match; we're not equivalent
12438                    if (DEBUG_FILTERS) {
12439                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12440                                + " package: " + applicationInfo.packageName
12441                                + " activity: " + intent.activity.className
12442                                + " origPrio: " + intent.getPriority());
12443                    }
12444                    intent.setPriority(0);
12445                    return;
12446                }
12447            }
12448
12449            // find matching schemes subsets
12450            final Iterator<String> schemesIterator = intent.schemesIterator();
12451            if (schemesIterator != null) {
12452                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12453                        schemesIterator);
12454                if (intentListCopy.size() == 0) {
12455                    // no more intents to match; we're not equivalent
12456                    if (DEBUG_FILTERS) {
12457                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12458                                + " package: " + applicationInfo.packageName
12459                                + " activity: " + intent.activity.className
12460                                + " origPrio: " + intent.getPriority());
12461                    }
12462                    intent.setPriority(0);
12463                    return;
12464                }
12465            }
12466
12467            // find matching authorities subsets
12468            final Iterator<IntentFilter.AuthorityEntry>
12469                    authoritiesIterator = intent.authoritiesIterator();
12470            if (authoritiesIterator != null) {
12471                getIntentListSubset(intentListCopy,
12472                        new AuthoritiesIterGenerator(),
12473                        authoritiesIterator);
12474                if (intentListCopy.size() == 0) {
12475                    // no more intents to match; we're not equivalent
12476                    if (DEBUG_FILTERS) {
12477                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12478                                + " package: " + applicationInfo.packageName
12479                                + " activity: " + intent.activity.className
12480                                + " origPrio: " + intent.getPriority());
12481                    }
12482                    intent.setPriority(0);
12483                    return;
12484                }
12485            }
12486
12487            // we found matching filter(s); app gets the max priority of all intents
12488            int cappedPriority = 0;
12489            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12490                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12491            }
12492            if (intent.getPriority() > cappedPriority) {
12493                if (DEBUG_FILTERS) {
12494                    Slog.i(TAG, "Found matching filter(s);"
12495                            + " cap priority to " + cappedPriority + ";"
12496                            + " package: " + applicationInfo.packageName
12497                            + " activity: " + intent.activity.className
12498                            + " origPrio: " + intent.getPriority());
12499                }
12500                intent.setPriority(cappedPriority);
12501                return;
12502            }
12503            // all this for nothing; the requested priority was <= what was on the system
12504        }
12505
12506        public final void addActivity(PackageParser.Activity a, String type) {
12507            mActivities.put(a.getComponentName(), a);
12508            if (DEBUG_SHOW_INFO)
12509                Log.v(
12510                TAG, "  " + type + " " +
12511                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12512            if (DEBUG_SHOW_INFO)
12513                Log.v(TAG, "    Class=" + a.info.name);
12514            final int NI = a.intents.size();
12515            for (int j=0; j<NI; j++) {
12516                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12517                if ("activity".equals(type)) {
12518                    final PackageSetting ps =
12519                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12520                    final List<PackageParser.Activity> systemActivities =
12521                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12522                    adjustPriority(systemActivities, intent);
12523                }
12524                if (DEBUG_SHOW_INFO) {
12525                    Log.v(TAG, "    IntentFilter:");
12526                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12527                }
12528                if (!intent.debugCheck()) {
12529                    Log.w(TAG, "==> For Activity " + a.info.name);
12530                }
12531                addFilter(intent);
12532            }
12533        }
12534
12535        public final void removeActivity(PackageParser.Activity a, String type) {
12536            mActivities.remove(a.getComponentName());
12537            if (DEBUG_SHOW_INFO) {
12538                Log.v(TAG, "  " + type + " "
12539                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12540                                : a.info.name) + ":");
12541                Log.v(TAG, "    Class=" + a.info.name);
12542            }
12543            final int NI = a.intents.size();
12544            for (int j=0; j<NI; j++) {
12545                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12546                if (DEBUG_SHOW_INFO) {
12547                    Log.v(TAG, "    IntentFilter:");
12548                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12549                }
12550                removeFilter(intent);
12551            }
12552        }
12553
12554        @Override
12555        protected boolean allowFilterResult(
12556                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12557            ActivityInfo filterAi = filter.activity.info;
12558            for (int i=dest.size()-1; i>=0; i--) {
12559                ActivityInfo destAi = dest.get(i).activityInfo;
12560                if (destAi.name == filterAi.name
12561                        && destAi.packageName == filterAi.packageName) {
12562                    return false;
12563                }
12564            }
12565            return true;
12566        }
12567
12568        @Override
12569        protected ActivityIntentInfo[] newArray(int size) {
12570            return new ActivityIntentInfo[size];
12571        }
12572
12573        @Override
12574        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12575            if (!sUserManager.exists(userId)) return true;
12576            PackageParser.Package p = filter.activity.owner;
12577            if (p != null) {
12578                PackageSetting ps = (PackageSetting)p.mExtras;
12579                if (ps != null) {
12580                    // System apps are never considered stopped for purposes of
12581                    // filtering, because there may be no way for the user to
12582                    // actually re-launch them.
12583                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12584                            && ps.getStopped(userId);
12585                }
12586            }
12587            return false;
12588        }
12589
12590        @Override
12591        protected boolean isPackageForFilter(String packageName,
12592                PackageParser.ActivityIntentInfo info) {
12593            return packageName.equals(info.activity.owner.packageName);
12594        }
12595
12596        @Override
12597        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12598                int match, int userId) {
12599            if (!sUserManager.exists(userId)) return null;
12600            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12601                return null;
12602            }
12603            final PackageParser.Activity activity = info.activity;
12604            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12605            if (ps == null) {
12606                return null;
12607            }
12608            final PackageUserState userState = ps.readUserState(userId);
12609            ActivityInfo ai =
12610                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12611            if (ai == null) {
12612                return null;
12613            }
12614            final boolean matchExplicitlyVisibleOnly =
12615                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12616            final boolean matchVisibleToInstantApp =
12617                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12618            final boolean componentVisible =
12619                    matchVisibleToInstantApp
12620                    && info.isVisibleToInstantApp()
12621                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12622            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12623            // throw out filters that aren't visible to ephemeral apps
12624            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12625                return null;
12626            }
12627            // throw out instant app filters if we're not explicitly requesting them
12628            if (!matchInstantApp && userState.instantApp) {
12629                return null;
12630            }
12631            // throw out instant app filters if updates are available; will trigger
12632            // instant app resolution
12633            if (userState.instantApp && ps.isUpdateAvailable()) {
12634                return null;
12635            }
12636            final ResolveInfo res = new ResolveInfo();
12637            res.activityInfo = ai;
12638            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12639                res.filter = info;
12640            }
12641            if (info != null) {
12642                res.handleAllWebDataURI = info.handleAllWebDataURI();
12643            }
12644            res.priority = info.getPriority();
12645            res.preferredOrder = activity.owner.mPreferredOrder;
12646            //System.out.println("Result: " + res.activityInfo.className +
12647            //                   " = " + res.priority);
12648            res.match = match;
12649            res.isDefault = info.hasDefault;
12650            res.labelRes = info.labelRes;
12651            res.nonLocalizedLabel = info.nonLocalizedLabel;
12652            if (userNeedsBadging(userId)) {
12653                res.noResourceId = true;
12654            } else {
12655                res.icon = info.icon;
12656            }
12657            res.iconResourceId = info.icon;
12658            res.system = res.activityInfo.applicationInfo.isSystemApp();
12659            res.isInstantAppAvailable = userState.instantApp;
12660            return res;
12661        }
12662
12663        @Override
12664        protected void sortResults(List<ResolveInfo> results) {
12665            Collections.sort(results, mResolvePrioritySorter);
12666        }
12667
12668        @Override
12669        protected void dumpFilter(PrintWriter out, String prefix,
12670                PackageParser.ActivityIntentInfo filter) {
12671            out.print(prefix); out.print(
12672                    Integer.toHexString(System.identityHashCode(filter.activity)));
12673                    out.print(' ');
12674                    filter.activity.printComponentShortName(out);
12675                    out.print(" filter ");
12676                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12677        }
12678
12679        @Override
12680        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12681            return filter.activity;
12682        }
12683
12684        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12685            PackageParser.Activity activity = (PackageParser.Activity)label;
12686            out.print(prefix); out.print(
12687                    Integer.toHexString(System.identityHashCode(activity)));
12688                    out.print(' ');
12689                    activity.printComponentShortName(out);
12690            if (count > 1) {
12691                out.print(" ("); out.print(count); out.print(" filters)");
12692            }
12693            out.println();
12694        }
12695
12696        // Keys are String (activity class name), values are Activity.
12697        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12698                = new ArrayMap<ComponentName, PackageParser.Activity>();
12699        private int mFlags;
12700    }
12701
12702    private final class ServiceIntentResolver
12703            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12704        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12705                boolean defaultOnly, int userId) {
12706            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12707            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12708        }
12709
12710        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12711                int userId) {
12712            if (!sUserManager.exists(userId)) return null;
12713            mFlags = flags;
12714            return super.queryIntent(intent, resolvedType,
12715                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12716                    userId);
12717        }
12718
12719        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12720                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12721            if (!sUserManager.exists(userId)) return null;
12722            if (packageServices == null) {
12723                return null;
12724            }
12725            mFlags = flags;
12726            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12727            final int N = packageServices.size();
12728            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12729                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12730
12731            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12732            for (int i = 0; i < N; ++i) {
12733                intentFilters = packageServices.get(i).intents;
12734                if (intentFilters != null && intentFilters.size() > 0) {
12735                    PackageParser.ServiceIntentInfo[] array =
12736                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12737                    intentFilters.toArray(array);
12738                    listCut.add(array);
12739                }
12740            }
12741            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12742        }
12743
12744        public final void addService(PackageParser.Service s) {
12745            mServices.put(s.getComponentName(), s);
12746            if (DEBUG_SHOW_INFO) {
12747                Log.v(TAG, "  "
12748                        + (s.info.nonLocalizedLabel != null
12749                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12750                Log.v(TAG, "    Class=" + s.info.name);
12751            }
12752            final int NI = s.intents.size();
12753            int j;
12754            for (j=0; j<NI; j++) {
12755                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12756                if (DEBUG_SHOW_INFO) {
12757                    Log.v(TAG, "    IntentFilter:");
12758                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12759                }
12760                if (!intent.debugCheck()) {
12761                    Log.w(TAG, "==> For Service " + s.info.name);
12762                }
12763                addFilter(intent);
12764            }
12765        }
12766
12767        public final void removeService(PackageParser.Service s) {
12768            mServices.remove(s.getComponentName());
12769            if (DEBUG_SHOW_INFO) {
12770                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12771                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12772                Log.v(TAG, "    Class=" + s.info.name);
12773            }
12774            final int NI = s.intents.size();
12775            int j;
12776            for (j=0; j<NI; j++) {
12777                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12778                if (DEBUG_SHOW_INFO) {
12779                    Log.v(TAG, "    IntentFilter:");
12780                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12781                }
12782                removeFilter(intent);
12783            }
12784        }
12785
12786        @Override
12787        protected boolean allowFilterResult(
12788                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12789            ServiceInfo filterSi = filter.service.info;
12790            for (int i=dest.size()-1; i>=0; i--) {
12791                ServiceInfo destAi = dest.get(i).serviceInfo;
12792                if (destAi.name == filterSi.name
12793                        && destAi.packageName == filterSi.packageName) {
12794                    return false;
12795                }
12796            }
12797            return true;
12798        }
12799
12800        @Override
12801        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12802            return new PackageParser.ServiceIntentInfo[size];
12803        }
12804
12805        @Override
12806        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12807            if (!sUserManager.exists(userId)) return true;
12808            PackageParser.Package p = filter.service.owner;
12809            if (p != null) {
12810                PackageSetting ps = (PackageSetting)p.mExtras;
12811                if (ps != null) {
12812                    // System apps are never considered stopped for purposes of
12813                    // filtering, because there may be no way for the user to
12814                    // actually re-launch them.
12815                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12816                            && ps.getStopped(userId);
12817                }
12818            }
12819            return false;
12820        }
12821
12822        @Override
12823        protected boolean isPackageForFilter(String packageName,
12824                PackageParser.ServiceIntentInfo info) {
12825            return packageName.equals(info.service.owner.packageName);
12826        }
12827
12828        @Override
12829        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12830                int match, int userId) {
12831            if (!sUserManager.exists(userId)) return null;
12832            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12833            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12834                return null;
12835            }
12836            final PackageParser.Service service = info.service;
12837            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12838            if (ps == null) {
12839                return null;
12840            }
12841            final PackageUserState userState = ps.readUserState(userId);
12842            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12843                    userState, userId);
12844            if (si == null) {
12845                return null;
12846            }
12847            final boolean matchVisibleToInstantApp =
12848                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12849            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12850            // throw out filters that aren't visible to ephemeral apps
12851            if (matchVisibleToInstantApp
12852                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12853                return null;
12854            }
12855            // throw out ephemeral filters if we're not explicitly requesting them
12856            if (!isInstantApp && userState.instantApp) {
12857                return null;
12858            }
12859            // throw out instant app filters if updates are available; will trigger
12860            // instant app resolution
12861            if (userState.instantApp && ps.isUpdateAvailable()) {
12862                return null;
12863            }
12864            final ResolveInfo res = new ResolveInfo();
12865            res.serviceInfo = si;
12866            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12867                res.filter = filter;
12868            }
12869            res.priority = info.getPriority();
12870            res.preferredOrder = service.owner.mPreferredOrder;
12871            res.match = match;
12872            res.isDefault = info.hasDefault;
12873            res.labelRes = info.labelRes;
12874            res.nonLocalizedLabel = info.nonLocalizedLabel;
12875            res.icon = info.icon;
12876            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12877            return res;
12878        }
12879
12880        @Override
12881        protected void sortResults(List<ResolveInfo> results) {
12882            Collections.sort(results, mResolvePrioritySorter);
12883        }
12884
12885        @Override
12886        protected void dumpFilter(PrintWriter out, String prefix,
12887                PackageParser.ServiceIntentInfo filter) {
12888            out.print(prefix); out.print(
12889                    Integer.toHexString(System.identityHashCode(filter.service)));
12890                    out.print(' ');
12891                    filter.service.printComponentShortName(out);
12892                    out.print(" filter ");
12893                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12894                    if (filter.service.info.permission != null) {
12895                        out.print(" permission "); out.println(filter.service.info.permission);
12896                    } else {
12897                        out.println();
12898                    }
12899        }
12900
12901        @Override
12902        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12903            return filter.service;
12904        }
12905
12906        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12907            PackageParser.Service service = (PackageParser.Service)label;
12908            out.print(prefix); out.print(
12909                    Integer.toHexString(System.identityHashCode(service)));
12910                    out.print(' ');
12911                    service.printComponentShortName(out);
12912            if (count > 1) {
12913                out.print(" ("); out.print(count); out.print(" filters)");
12914            }
12915            out.println();
12916        }
12917
12918//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12919//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12920//            final List<ResolveInfo> retList = Lists.newArrayList();
12921//            while (i.hasNext()) {
12922//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12923//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12924//                    retList.add(resolveInfo);
12925//                }
12926//            }
12927//            return retList;
12928//        }
12929
12930        // Keys are String (activity class name), values are Activity.
12931        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12932                = new ArrayMap<ComponentName, PackageParser.Service>();
12933        private int mFlags;
12934    }
12935
12936    private final class ProviderIntentResolver
12937            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12938        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12939                boolean defaultOnly, int userId) {
12940            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12941            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12942        }
12943
12944        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12945                int userId) {
12946            if (!sUserManager.exists(userId))
12947                return null;
12948            mFlags = flags;
12949            return super.queryIntent(intent, resolvedType,
12950                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12951                    userId);
12952        }
12953
12954        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12955                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12956            if (!sUserManager.exists(userId))
12957                return null;
12958            if (packageProviders == null) {
12959                return null;
12960            }
12961            mFlags = flags;
12962            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12963            final int N = packageProviders.size();
12964            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12965                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12966
12967            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12968            for (int i = 0; i < N; ++i) {
12969                intentFilters = packageProviders.get(i).intents;
12970                if (intentFilters != null && intentFilters.size() > 0) {
12971                    PackageParser.ProviderIntentInfo[] array =
12972                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12973                    intentFilters.toArray(array);
12974                    listCut.add(array);
12975                }
12976            }
12977            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12978        }
12979
12980        public final void addProvider(PackageParser.Provider p) {
12981            if (mProviders.containsKey(p.getComponentName())) {
12982                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12983                return;
12984            }
12985
12986            mProviders.put(p.getComponentName(), p);
12987            if (DEBUG_SHOW_INFO) {
12988                Log.v(TAG, "  "
12989                        + (p.info.nonLocalizedLabel != null
12990                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12991                Log.v(TAG, "    Class=" + p.info.name);
12992            }
12993            final int NI = p.intents.size();
12994            int j;
12995            for (j = 0; j < NI; j++) {
12996                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12997                if (DEBUG_SHOW_INFO) {
12998                    Log.v(TAG, "    IntentFilter:");
12999                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13000                }
13001                if (!intent.debugCheck()) {
13002                    Log.w(TAG, "==> For Provider " + p.info.name);
13003                }
13004                addFilter(intent);
13005            }
13006        }
13007
13008        public final void removeProvider(PackageParser.Provider p) {
13009            mProviders.remove(p.getComponentName());
13010            if (DEBUG_SHOW_INFO) {
13011                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13012                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13013                Log.v(TAG, "    Class=" + p.info.name);
13014            }
13015            final int NI = p.intents.size();
13016            int j;
13017            for (j = 0; j < NI; j++) {
13018                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13019                if (DEBUG_SHOW_INFO) {
13020                    Log.v(TAG, "    IntentFilter:");
13021                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13022                }
13023                removeFilter(intent);
13024            }
13025        }
13026
13027        @Override
13028        protected boolean allowFilterResult(
13029                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13030            ProviderInfo filterPi = filter.provider.info;
13031            for (int i = dest.size() - 1; i >= 0; i--) {
13032                ProviderInfo destPi = dest.get(i).providerInfo;
13033                if (destPi.name == filterPi.name
13034                        && destPi.packageName == filterPi.packageName) {
13035                    return false;
13036                }
13037            }
13038            return true;
13039        }
13040
13041        @Override
13042        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13043            return new PackageParser.ProviderIntentInfo[size];
13044        }
13045
13046        @Override
13047        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13048            if (!sUserManager.exists(userId))
13049                return true;
13050            PackageParser.Package p = filter.provider.owner;
13051            if (p != null) {
13052                PackageSetting ps = (PackageSetting) p.mExtras;
13053                if (ps != null) {
13054                    // System apps are never considered stopped for purposes of
13055                    // filtering, because there may be no way for the user to
13056                    // actually re-launch them.
13057                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13058                            && ps.getStopped(userId);
13059                }
13060            }
13061            return false;
13062        }
13063
13064        @Override
13065        protected boolean isPackageForFilter(String packageName,
13066                PackageParser.ProviderIntentInfo info) {
13067            return packageName.equals(info.provider.owner.packageName);
13068        }
13069
13070        @Override
13071        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13072                int match, int userId) {
13073            if (!sUserManager.exists(userId))
13074                return null;
13075            final PackageParser.ProviderIntentInfo info = filter;
13076            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13077                return null;
13078            }
13079            final PackageParser.Provider provider = info.provider;
13080            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13081            if (ps == null) {
13082                return null;
13083            }
13084            final PackageUserState userState = ps.readUserState(userId);
13085            final boolean matchVisibleToInstantApp =
13086                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13087            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13088            // throw out filters that aren't visible to instant applications
13089            if (matchVisibleToInstantApp
13090                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13091                return null;
13092            }
13093            // throw out instant application filters if we're not explicitly requesting them
13094            if (!isInstantApp && userState.instantApp) {
13095                return null;
13096            }
13097            // throw out instant application filters if updates are available; will trigger
13098            // instant application resolution
13099            if (userState.instantApp && ps.isUpdateAvailable()) {
13100                return null;
13101            }
13102            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13103                    userState, userId);
13104            if (pi == null) {
13105                return null;
13106            }
13107            final ResolveInfo res = new ResolveInfo();
13108            res.providerInfo = pi;
13109            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13110                res.filter = filter;
13111            }
13112            res.priority = info.getPriority();
13113            res.preferredOrder = provider.owner.mPreferredOrder;
13114            res.match = match;
13115            res.isDefault = info.hasDefault;
13116            res.labelRes = info.labelRes;
13117            res.nonLocalizedLabel = info.nonLocalizedLabel;
13118            res.icon = info.icon;
13119            res.system = res.providerInfo.applicationInfo.isSystemApp();
13120            return res;
13121        }
13122
13123        @Override
13124        protected void sortResults(List<ResolveInfo> results) {
13125            Collections.sort(results, mResolvePrioritySorter);
13126        }
13127
13128        @Override
13129        protected void dumpFilter(PrintWriter out, String prefix,
13130                PackageParser.ProviderIntentInfo filter) {
13131            out.print(prefix);
13132            out.print(
13133                    Integer.toHexString(System.identityHashCode(filter.provider)));
13134            out.print(' ');
13135            filter.provider.printComponentShortName(out);
13136            out.print(" filter ");
13137            out.println(Integer.toHexString(System.identityHashCode(filter)));
13138        }
13139
13140        @Override
13141        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13142            return filter.provider;
13143        }
13144
13145        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13146            PackageParser.Provider provider = (PackageParser.Provider)label;
13147            out.print(prefix); out.print(
13148                    Integer.toHexString(System.identityHashCode(provider)));
13149                    out.print(' ');
13150                    provider.printComponentShortName(out);
13151            if (count > 1) {
13152                out.print(" ("); out.print(count); out.print(" filters)");
13153            }
13154            out.println();
13155        }
13156
13157        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13158                = new ArrayMap<ComponentName, PackageParser.Provider>();
13159        private int mFlags;
13160    }
13161
13162    static final class InstantAppIntentResolver
13163            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13164            AuxiliaryResolveInfo.AuxiliaryFilter> {
13165        /**
13166         * The result that has the highest defined order. Ordering applies on a
13167         * per-package basis. Mapping is from package name to Pair of order and
13168         * EphemeralResolveInfo.
13169         * <p>
13170         * NOTE: This is implemented as a field variable for convenience and efficiency.
13171         * By having a field variable, we're able to track filter ordering as soon as
13172         * a non-zero order is defined. Otherwise, multiple loops across the result set
13173         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13174         * this needs to be contained entirely within {@link #filterResults}.
13175         */
13176        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13177
13178        @Override
13179        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13180            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13181        }
13182
13183        @Override
13184        protected boolean isPackageForFilter(String packageName,
13185                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13186            return true;
13187        }
13188
13189        @Override
13190        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13191                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13192            if (!sUserManager.exists(userId)) {
13193                return null;
13194            }
13195            final String packageName = responseObj.resolveInfo.getPackageName();
13196            final Integer order = responseObj.getOrder();
13197            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13198                    mOrderResult.get(packageName);
13199            // ordering is enabled and this item's order isn't high enough
13200            if (lastOrderResult != null && lastOrderResult.first >= order) {
13201                return null;
13202            }
13203            final InstantAppResolveInfo res = responseObj.resolveInfo;
13204            if (order > 0) {
13205                // non-zero order, enable ordering
13206                mOrderResult.put(packageName, new Pair<>(order, res));
13207            }
13208            return responseObj;
13209        }
13210
13211        @Override
13212        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13213            // only do work if ordering is enabled [most of the time it won't be]
13214            if (mOrderResult.size() == 0) {
13215                return;
13216            }
13217            int resultSize = results.size();
13218            for (int i = 0; i < resultSize; i++) {
13219                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13220                final String packageName = info.getPackageName();
13221                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13222                if (savedInfo == null) {
13223                    // package doesn't having ordering
13224                    continue;
13225                }
13226                if (savedInfo.second == info) {
13227                    // circled back to the highest ordered item; remove from order list
13228                    mOrderResult.remove(packageName);
13229                    if (mOrderResult.size() == 0) {
13230                        // no more ordered items
13231                        break;
13232                    }
13233                    continue;
13234                }
13235                // item has a worse order, remove it from the result list
13236                results.remove(i);
13237                resultSize--;
13238                i--;
13239            }
13240        }
13241    }
13242
13243    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13244            new Comparator<ResolveInfo>() {
13245        public int compare(ResolveInfo r1, ResolveInfo r2) {
13246            int v1 = r1.priority;
13247            int v2 = r2.priority;
13248            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13249            if (v1 != v2) {
13250                return (v1 > v2) ? -1 : 1;
13251            }
13252            v1 = r1.preferredOrder;
13253            v2 = r2.preferredOrder;
13254            if (v1 != v2) {
13255                return (v1 > v2) ? -1 : 1;
13256            }
13257            if (r1.isDefault != r2.isDefault) {
13258                return r1.isDefault ? -1 : 1;
13259            }
13260            v1 = r1.match;
13261            v2 = r2.match;
13262            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13263            if (v1 != v2) {
13264                return (v1 > v2) ? -1 : 1;
13265            }
13266            if (r1.system != r2.system) {
13267                return r1.system ? -1 : 1;
13268            }
13269            if (r1.activityInfo != null) {
13270                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13271            }
13272            if (r1.serviceInfo != null) {
13273                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13274            }
13275            if (r1.providerInfo != null) {
13276                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13277            }
13278            return 0;
13279        }
13280    };
13281
13282    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13283            new Comparator<ProviderInfo>() {
13284        public int compare(ProviderInfo p1, ProviderInfo p2) {
13285            final int v1 = p1.initOrder;
13286            final int v2 = p2.initOrder;
13287            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13288        }
13289    };
13290
13291    @Override
13292    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13293            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13294            final int[] userIds, int[] instantUserIds) {
13295        mHandler.post(new Runnable() {
13296            @Override
13297            public void run() {
13298                try {
13299                    final IActivityManager am = ActivityManager.getService();
13300                    if (am == null) return;
13301                    final int[] resolvedUserIds;
13302                    if (userIds == null) {
13303                        resolvedUserIds = am.getRunningUserIds();
13304                    } else {
13305                        resolvedUserIds = userIds;
13306                    }
13307                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13308                            resolvedUserIds, false);
13309                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13310                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13311                                instantUserIds, true);
13312                    }
13313                } catch (RemoteException ex) {
13314                }
13315            }
13316        });
13317    }
13318
13319    @Override
13320    public void notifyPackageAdded(String packageName) {
13321        final PackageListObserver[] observers;
13322        synchronized (mPackages) {
13323            if (mPackageListObservers.size() == 0) {
13324                return;
13325            }
13326            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13327        }
13328        for (int i = observers.length - 1; i >= 0; --i) {
13329            observers[i].onPackageAdded(packageName);
13330        }
13331    }
13332
13333    @Override
13334    public void notifyPackageRemoved(String packageName) {
13335        final PackageListObserver[] observers;
13336        synchronized (mPackages) {
13337            if (mPackageListObservers.size() == 0) {
13338                return;
13339            }
13340            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13341        }
13342        for (int i = observers.length - 1; i >= 0; --i) {
13343            observers[i].onPackageRemoved(packageName);
13344        }
13345    }
13346
13347    /**
13348     * Sends a broadcast for the given action.
13349     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13350     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13351     * the system and applications allowed to see instant applications to receive package
13352     * lifecycle events for instant applications.
13353     */
13354    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13355            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13356            int[] userIds, boolean isInstantApp)
13357                    throws RemoteException {
13358        for (int id : userIds) {
13359            final Intent intent = new Intent(action,
13360                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13361            final String[] requiredPermissions =
13362                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13363            if (extras != null) {
13364                intent.putExtras(extras);
13365            }
13366            if (targetPkg != null) {
13367                intent.setPackage(targetPkg);
13368            }
13369            // Modify the UID when posting to other users
13370            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13371            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13372                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13373                intent.putExtra(Intent.EXTRA_UID, uid);
13374            }
13375            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13376            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13377            if (DEBUG_BROADCASTS) {
13378                RuntimeException here = new RuntimeException("here");
13379                here.fillInStackTrace();
13380                Slog.d(TAG, "Sending to user " + id + ": "
13381                        + intent.toShortString(false, true, false, false)
13382                        + " " + intent.getExtras(), here);
13383            }
13384            am.broadcastIntent(null, intent, null, finishedReceiver,
13385                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13386                    null, finishedReceiver != null, false, id);
13387        }
13388    }
13389
13390    /**
13391     * Check if the external storage media is available. This is true if there
13392     * is a mounted external storage medium or if the external storage is
13393     * emulated.
13394     */
13395    private boolean isExternalMediaAvailable() {
13396        return mMediaMounted || Environment.isExternalStorageEmulated();
13397    }
13398
13399    @Override
13400    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13401        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13402            return null;
13403        }
13404        if (!isExternalMediaAvailable()) {
13405                // If the external storage is no longer mounted at this point,
13406                // the caller may not have been able to delete all of this
13407                // packages files and can not delete any more.  Bail.
13408            return null;
13409        }
13410        synchronized (mPackages) {
13411            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13412            if (lastPackage != null) {
13413                pkgs.remove(lastPackage);
13414            }
13415            if (pkgs.size() > 0) {
13416                return pkgs.get(0);
13417            }
13418        }
13419        return null;
13420    }
13421
13422    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13423        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13424                userId, andCode ? 1 : 0, packageName);
13425        if (mSystemReady) {
13426            msg.sendToTarget();
13427        } else {
13428            if (mPostSystemReadyMessages == null) {
13429                mPostSystemReadyMessages = new ArrayList<>();
13430            }
13431            mPostSystemReadyMessages.add(msg);
13432        }
13433    }
13434
13435    void startCleaningPackages() {
13436        // reader
13437        if (!isExternalMediaAvailable()) {
13438            return;
13439        }
13440        synchronized (mPackages) {
13441            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13442                return;
13443            }
13444        }
13445        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13446        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13447        IActivityManager am = ActivityManager.getService();
13448        if (am != null) {
13449            int dcsUid = -1;
13450            synchronized (mPackages) {
13451                if (!mDefaultContainerWhitelisted) {
13452                    mDefaultContainerWhitelisted = true;
13453                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13454                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13455                }
13456            }
13457            try {
13458                if (dcsUid > 0) {
13459                    am.backgroundWhitelistUid(dcsUid);
13460                }
13461                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13462                        UserHandle.USER_SYSTEM);
13463            } catch (RemoteException e) {
13464            }
13465        }
13466    }
13467
13468    /**
13469     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13470     * it is acting on behalf on an enterprise or the user).
13471     *
13472     * Note that the ordering of the conditionals in this method is important. The checks we perform
13473     * are as follows, in this order:
13474     *
13475     * 1) If the install is being performed by a system app, we can trust the app to have set the
13476     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13477     *    what it is.
13478     * 2) If the install is being performed by a device or profile owner app, the install reason
13479     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13480     *    set the install reason correctly. If the app targets an older SDK version where install
13481     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13482     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13483     * 3) In all other cases, the install is being performed by a regular app that is neither part
13484     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13485     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13486     *    set to enterprise policy and if so, change it to unknown instead.
13487     */
13488    private int fixUpInstallReason(String installerPackageName, int installerUid,
13489            int installReason) {
13490        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13491                == PERMISSION_GRANTED) {
13492            // If the install is being performed by a system app, we trust that app to have set the
13493            // install reason correctly.
13494            return installReason;
13495        }
13496
13497        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13498            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13499        if (dpm != null) {
13500            ComponentName owner = null;
13501            try {
13502                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13503                if (owner == null) {
13504                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13505                }
13506            } catch (RemoteException e) {
13507            }
13508            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13509                // If the install is being performed by a device or profile owner, the install
13510                // reason should be enterprise policy.
13511                return PackageManager.INSTALL_REASON_POLICY;
13512            }
13513        }
13514
13515        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13516            // If the install is being performed by a regular app (i.e. neither system app nor
13517            // device or profile owner), we have no reason to believe that the app is acting on
13518            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13519            // change it to unknown instead.
13520            return PackageManager.INSTALL_REASON_UNKNOWN;
13521        }
13522
13523        // If the install is being performed by a regular app and the install reason was set to any
13524        // value but enterprise policy, leave the install reason unchanged.
13525        return installReason;
13526    }
13527
13528    void installStage(String packageName, File stagedDir,
13529            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13530            String installerPackageName, int installerUid, UserHandle user,
13531            PackageParser.SigningDetails signingDetails) {
13532        if (DEBUG_INSTANT) {
13533            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13534                Slog.d(TAG, "Ephemeral install of " + packageName);
13535            }
13536        }
13537        final VerificationInfo verificationInfo = new VerificationInfo(
13538                sessionParams.originatingUri, sessionParams.referrerUri,
13539                sessionParams.originatingUid, installerUid);
13540
13541        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13542
13543        final Message msg = mHandler.obtainMessage(INIT_COPY);
13544        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13545                sessionParams.installReason);
13546        final InstallParams params = new InstallParams(origin, null, observer,
13547                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13548                verificationInfo, user, sessionParams.abiOverride,
13549                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13550        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13551        msg.obj = params;
13552
13553        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13554                System.identityHashCode(msg.obj));
13555        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13556                System.identityHashCode(msg.obj));
13557
13558        mHandler.sendMessage(msg);
13559    }
13560
13561    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13562            int userId) {
13563        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13564        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13565        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13566        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13567        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13568                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13569
13570        // Send a session commit broadcast
13571        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13572        info.installReason = pkgSetting.getInstallReason(userId);
13573        info.appPackageName = packageName;
13574        sendSessionCommitBroadcast(info, userId);
13575    }
13576
13577    @Override
13578    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13579            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13580        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13581            return;
13582        }
13583        Bundle extras = new Bundle(1);
13584        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13585        final int uid = UserHandle.getUid(
13586                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13587        extras.putInt(Intent.EXTRA_UID, uid);
13588
13589        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13590                packageName, extras, 0, null, null, userIds, instantUserIds);
13591        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13592            mHandler.post(() -> {
13593                        for (int userId : userIds) {
13594                            sendBootCompletedBroadcastToSystemApp(
13595                                    packageName, includeStopped, userId);
13596                        }
13597                    }
13598            );
13599        }
13600    }
13601
13602    /**
13603     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13604     * automatically without needing an explicit launch.
13605     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13606     */
13607    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13608            int userId) {
13609        // If user is not running, the app didn't miss any broadcast
13610        if (!mUserManagerInternal.isUserRunning(userId)) {
13611            return;
13612        }
13613        final IActivityManager am = ActivityManager.getService();
13614        try {
13615            // Deliver LOCKED_BOOT_COMPLETED first
13616            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13617                    .setPackage(packageName);
13618            if (includeStopped) {
13619                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13620            }
13621            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13622            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13623                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13624
13625            // Deliver BOOT_COMPLETED only if user is unlocked
13626            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13627                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13628                if (includeStopped) {
13629                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13630                }
13631                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13632                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13633            }
13634        } catch (RemoteException e) {
13635            throw e.rethrowFromSystemServer();
13636        }
13637    }
13638
13639    @Override
13640    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13641            int userId) {
13642        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13643        PackageSetting pkgSetting;
13644        final int callingUid = Binder.getCallingUid();
13645        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13646                true /* requireFullPermission */, true /* checkShell */,
13647                "setApplicationHiddenSetting for user " + userId);
13648
13649        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13650            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13651            return false;
13652        }
13653
13654        long callingId = Binder.clearCallingIdentity();
13655        try {
13656            boolean sendAdded = false;
13657            boolean sendRemoved = false;
13658            // writer
13659            synchronized (mPackages) {
13660                pkgSetting = mSettings.mPackages.get(packageName);
13661                if (pkgSetting == null) {
13662                    return false;
13663                }
13664                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13665                    return false;
13666                }
13667                // Do not allow "android" is being disabled
13668                if ("android".equals(packageName)) {
13669                    Slog.w(TAG, "Cannot hide package: android");
13670                    return false;
13671                }
13672                // Cannot hide static shared libs as they are considered
13673                // a part of the using app (emulating static linking). Also
13674                // static libs are installed always on internal storage.
13675                PackageParser.Package pkg = mPackages.get(packageName);
13676                if (pkg != null && pkg.staticSharedLibName != null) {
13677                    Slog.w(TAG, "Cannot hide package: " + packageName
13678                            + " providing static shared library: "
13679                            + pkg.staticSharedLibName);
13680                    return false;
13681                }
13682                // Only allow protected packages to hide themselves.
13683                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13684                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13685                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13686                    return false;
13687                }
13688
13689                if (pkgSetting.getHidden(userId) != hidden) {
13690                    pkgSetting.setHidden(hidden, userId);
13691                    mSettings.writePackageRestrictionsLPr(userId);
13692                    if (hidden) {
13693                        sendRemoved = true;
13694                    } else {
13695                        sendAdded = true;
13696                    }
13697                }
13698            }
13699            if (sendAdded) {
13700                sendPackageAddedForUser(packageName, pkgSetting, userId);
13701                return true;
13702            }
13703            if (sendRemoved) {
13704                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13705                        "hiding pkg");
13706                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13707                return true;
13708            }
13709        } finally {
13710            Binder.restoreCallingIdentity(callingId);
13711        }
13712        return false;
13713    }
13714
13715    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13716            int userId) {
13717        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13718        info.removedPackage = packageName;
13719        info.installerPackageName = pkgSetting.installerPackageName;
13720        info.removedUsers = new int[] {userId};
13721        info.broadcastUsers = new int[] {userId};
13722        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13723        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13724    }
13725
13726    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13727        if (pkgList.length > 0) {
13728            Bundle extras = new Bundle(1);
13729            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13730
13731            sendPackageBroadcast(
13732                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13733                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13734                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13735                    new int[] {userId}, null);
13736        }
13737    }
13738
13739    /**
13740     * Returns true if application is not found or there was an error. Otherwise it returns
13741     * the hidden state of the package for the given user.
13742     */
13743    @Override
13744    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13745        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13746        final int callingUid = Binder.getCallingUid();
13747        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13748                true /* requireFullPermission */, false /* checkShell */,
13749                "getApplicationHidden for user " + userId);
13750        PackageSetting ps;
13751        long callingId = Binder.clearCallingIdentity();
13752        try {
13753            // writer
13754            synchronized (mPackages) {
13755                ps = mSettings.mPackages.get(packageName);
13756                if (ps == null) {
13757                    return true;
13758                }
13759                if (filterAppAccessLPr(ps, callingUid, userId)) {
13760                    return true;
13761                }
13762                return ps.getHidden(userId);
13763            }
13764        } finally {
13765            Binder.restoreCallingIdentity(callingId);
13766        }
13767    }
13768
13769    /**
13770     * @hide
13771     */
13772    @Override
13773    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13774            int installReason) {
13775        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13776                null);
13777        PackageSetting pkgSetting;
13778        final int callingUid = Binder.getCallingUid();
13779        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13780                true /* requireFullPermission */, true /* checkShell */,
13781                "installExistingPackage for user " + userId);
13782        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13783            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13784        }
13785
13786        long callingId = Binder.clearCallingIdentity();
13787        try {
13788            boolean installed = false;
13789            final boolean instantApp =
13790                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13791            final boolean fullApp =
13792                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13793
13794            // writer
13795            synchronized (mPackages) {
13796                pkgSetting = mSettings.mPackages.get(packageName);
13797                if (pkgSetting == null) {
13798                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13799                }
13800                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13801                    // only allow the existing package to be used if it's installed as a full
13802                    // application for at least one user
13803                    boolean installAllowed = false;
13804                    for (int checkUserId : sUserManager.getUserIds()) {
13805                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13806                        if (installAllowed) {
13807                            break;
13808                        }
13809                    }
13810                    if (!installAllowed) {
13811                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13812                    }
13813                }
13814                if (!pkgSetting.getInstalled(userId)) {
13815                    pkgSetting.setInstalled(true, userId);
13816                    pkgSetting.setHidden(false, userId);
13817                    pkgSetting.setInstallReason(installReason, userId);
13818                    mSettings.writePackageRestrictionsLPr(userId);
13819                    mSettings.writeKernelMappingLPr(pkgSetting);
13820                    installed = true;
13821                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13822                    // upgrade app from instant to full; we don't allow app downgrade
13823                    installed = true;
13824                }
13825                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13826            }
13827
13828            if (installed) {
13829                if (pkgSetting.pkg != null) {
13830                    synchronized (mInstallLock) {
13831                        // We don't need to freeze for a brand new install
13832                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13833                    }
13834                }
13835                sendPackageAddedForUser(packageName, pkgSetting, userId);
13836                synchronized (mPackages) {
13837                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13838                }
13839            }
13840        } finally {
13841            Binder.restoreCallingIdentity(callingId);
13842        }
13843
13844        return PackageManager.INSTALL_SUCCEEDED;
13845    }
13846
13847    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13848            boolean instantApp, boolean fullApp) {
13849        // no state specified; do nothing
13850        if (!instantApp && !fullApp) {
13851            return;
13852        }
13853        if (userId != UserHandle.USER_ALL) {
13854            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13855                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13856            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13857                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13858            }
13859        } else {
13860            for (int currentUserId : sUserManager.getUserIds()) {
13861                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13862                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13863                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13864                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13865                }
13866            }
13867        }
13868    }
13869
13870    boolean isUserRestricted(int userId, String restrictionKey) {
13871        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13872        if (restrictions.getBoolean(restrictionKey, false)) {
13873            Log.w(TAG, "User is restricted: " + restrictionKey);
13874            return true;
13875        }
13876        return false;
13877    }
13878
13879    @Override
13880    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13881            int userId) {
13882        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13883        final int callingUid = Binder.getCallingUid();
13884        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13885                true /* requireFullPermission */, true /* checkShell */,
13886                "setPackagesSuspended for user " + userId);
13887
13888        if (ArrayUtils.isEmpty(packageNames)) {
13889            return packageNames;
13890        }
13891
13892        // List of package names for whom the suspended state has changed.
13893        List<String> changedPackages = new ArrayList<>(packageNames.length);
13894        // List of package names for whom the suspended state is not set as requested in this
13895        // method.
13896        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13897        long callingId = Binder.clearCallingIdentity();
13898        try {
13899            for (int i = 0; i < packageNames.length; i++) {
13900                String packageName = packageNames[i];
13901                boolean changed = false;
13902                final int appId;
13903                synchronized (mPackages) {
13904                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13905                    if (pkgSetting == null
13906                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13907                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13908                                + "\". Skipping suspending/un-suspending.");
13909                        unactionedPackages.add(packageName);
13910                        continue;
13911                    }
13912                    appId = pkgSetting.appId;
13913                    if (pkgSetting.getSuspended(userId) != suspended) {
13914                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13915                            unactionedPackages.add(packageName);
13916                            continue;
13917                        }
13918                        pkgSetting.setSuspended(suspended, userId);
13919                        mSettings.writePackageRestrictionsLPr(userId);
13920                        changed = true;
13921                        changedPackages.add(packageName);
13922                    }
13923                }
13924
13925                if (changed && suspended) {
13926                    killApplication(packageName, UserHandle.getUid(userId, appId),
13927                            "suspending package");
13928                }
13929            }
13930        } finally {
13931            Binder.restoreCallingIdentity(callingId);
13932        }
13933
13934        if (!changedPackages.isEmpty()) {
13935            sendPackagesSuspendedForUser(changedPackages.toArray(
13936                    new String[changedPackages.size()]), userId, suspended);
13937        }
13938
13939        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13940    }
13941
13942    @Override
13943    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13944        final int callingUid = Binder.getCallingUid();
13945        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13946                true /* requireFullPermission */, false /* checkShell */,
13947                "isPackageSuspendedForUser for user " + userId);
13948        synchronized (mPackages) {
13949            final PackageSetting ps = mSettings.mPackages.get(packageName);
13950            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13951                throw new IllegalArgumentException("Unknown target package: " + packageName);
13952            }
13953            return ps.getSuspended(userId);
13954        }
13955    }
13956
13957    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13958        if (isPackageDeviceAdmin(packageName, userId)) {
13959            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13960                    + "\": has an active device admin");
13961            return false;
13962        }
13963
13964        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13965        if (packageName.equals(activeLauncherPackageName)) {
13966            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13967                    + "\": contains the active launcher");
13968            return false;
13969        }
13970
13971        if (packageName.equals(mRequiredInstallerPackage)) {
13972            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13973                    + "\": required for package installation");
13974            return false;
13975        }
13976
13977        if (packageName.equals(mRequiredUninstallerPackage)) {
13978            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13979                    + "\": required for package uninstallation");
13980            return false;
13981        }
13982
13983        if (packageName.equals(mRequiredVerifierPackage)) {
13984            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13985                    + "\": required for package verification");
13986            return false;
13987        }
13988
13989        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13990            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13991                    + "\": is the default dialer");
13992            return false;
13993        }
13994
13995        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13996            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13997                    + "\": protected package");
13998            return false;
13999        }
14000
14001        // Cannot suspend static shared libs as they are considered
14002        // a part of the using app (emulating static linking). Also
14003        // static libs are installed always on internal storage.
14004        PackageParser.Package pkg = mPackages.get(packageName);
14005        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14006            Slog.w(TAG, "Cannot suspend package: " + packageName
14007                    + " providing static shared library: "
14008                    + pkg.staticSharedLibName);
14009            return false;
14010        }
14011
14012        return true;
14013    }
14014
14015    private String getActiveLauncherPackageName(int userId) {
14016        Intent intent = new Intent(Intent.ACTION_MAIN);
14017        intent.addCategory(Intent.CATEGORY_HOME);
14018        ResolveInfo resolveInfo = resolveIntent(
14019                intent,
14020                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14021                PackageManager.MATCH_DEFAULT_ONLY,
14022                userId);
14023
14024        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14025    }
14026
14027    private String getDefaultDialerPackageName(int userId) {
14028        synchronized (mPackages) {
14029            return mSettings.getDefaultDialerPackageNameLPw(userId);
14030        }
14031    }
14032
14033    @Override
14034    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14035        mContext.enforceCallingOrSelfPermission(
14036                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14037                "Only package verification agents can verify applications");
14038
14039        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14040        final PackageVerificationResponse response = new PackageVerificationResponse(
14041                verificationCode, Binder.getCallingUid());
14042        msg.arg1 = id;
14043        msg.obj = response;
14044        mHandler.sendMessage(msg);
14045    }
14046
14047    @Override
14048    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14049            long millisecondsToDelay) {
14050        mContext.enforceCallingOrSelfPermission(
14051                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14052                "Only package verification agents can extend verification timeouts");
14053
14054        final PackageVerificationState state = mPendingVerification.get(id);
14055        final PackageVerificationResponse response = new PackageVerificationResponse(
14056                verificationCodeAtTimeout, Binder.getCallingUid());
14057
14058        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14059            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14060        }
14061        if (millisecondsToDelay < 0) {
14062            millisecondsToDelay = 0;
14063        }
14064        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14065                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14066            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14067        }
14068
14069        if ((state != null) && !state.timeoutExtended()) {
14070            state.extendTimeout();
14071
14072            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14073            msg.arg1 = id;
14074            msg.obj = response;
14075            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14076        }
14077    }
14078
14079    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14080            int verificationCode, UserHandle user) {
14081        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14082        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14083        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14084        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14085        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14086
14087        mContext.sendBroadcastAsUser(intent, user,
14088                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14089    }
14090
14091    private ComponentName matchComponentForVerifier(String packageName,
14092            List<ResolveInfo> receivers) {
14093        ActivityInfo targetReceiver = null;
14094
14095        final int NR = receivers.size();
14096        for (int i = 0; i < NR; i++) {
14097            final ResolveInfo info = receivers.get(i);
14098            if (info.activityInfo == null) {
14099                continue;
14100            }
14101
14102            if (packageName.equals(info.activityInfo.packageName)) {
14103                targetReceiver = info.activityInfo;
14104                break;
14105            }
14106        }
14107
14108        if (targetReceiver == null) {
14109            return null;
14110        }
14111
14112        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14113    }
14114
14115    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14116            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14117        if (pkgInfo.verifiers.length == 0) {
14118            return null;
14119        }
14120
14121        final int N = pkgInfo.verifiers.length;
14122        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14123        for (int i = 0; i < N; i++) {
14124            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14125
14126            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14127                    receivers);
14128            if (comp == null) {
14129                continue;
14130            }
14131
14132            final int verifierUid = getUidForVerifier(verifierInfo);
14133            if (verifierUid == -1) {
14134                continue;
14135            }
14136
14137            if (DEBUG_VERIFY) {
14138                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14139                        + " with the correct signature");
14140            }
14141            sufficientVerifiers.add(comp);
14142            verificationState.addSufficientVerifier(verifierUid);
14143        }
14144
14145        return sufficientVerifiers;
14146    }
14147
14148    private int getUidForVerifier(VerifierInfo verifierInfo) {
14149        synchronized (mPackages) {
14150            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14151            if (pkg == null) {
14152                return -1;
14153            } else if (pkg.mSigningDetails.signatures.length != 1) {
14154                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14155                        + " has more than one signature; ignoring");
14156                return -1;
14157            }
14158
14159            /*
14160             * If the public key of the package's signature does not match
14161             * our expected public key, then this is a different package and
14162             * we should skip.
14163             */
14164
14165            final byte[] expectedPublicKey;
14166            try {
14167                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14168                final PublicKey publicKey = verifierSig.getPublicKey();
14169                expectedPublicKey = publicKey.getEncoded();
14170            } catch (CertificateException e) {
14171                return -1;
14172            }
14173
14174            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14175
14176            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14177                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14178                        + " does not have the expected public key; ignoring");
14179                return -1;
14180            }
14181
14182            return pkg.applicationInfo.uid;
14183        }
14184    }
14185
14186    @Override
14187    public void finishPackageInstall(int token, boolean didLaunch) {
14188        enforceSystemOrRoot("Only the system is allowed to finish installs");
14189
14190        if (DEBUG_INSTALL) {
14191            Slog.v(TAG, "BM finishing package install for " + token);
14192        }
14193        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14194
14195        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14196        mHandler.sendMessage(msg);
14197    }
14198
14199    /**
14200     * Get the verification agent timeout.  Used for both the APK verifier and the
14201     * intent filter verifier.
14202     *
14203     * @return verification timeout in milliseconds
14204     */
14205    private long getVerificationTimeout() {
14206        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14207                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14208                DEFAULT_VERIFICATION_TIMEOUT);
14209    }
14210
14211    /**
14212     * Get the default verification agent response code.
14213     *
14214     * @return default verification response code
14215     */
14216    private int getDefaultVerificationResponse(UserHandle user) {
14217        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14218            return PackageManager.VERIFICATION_REJECT;
14219        }
14220        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14221                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14222                DEFAULT_VERIFICATION_RESPONSE);
14223    }
14224
14225    /**
14226     * Check whether or not package verification has been enabled.
14227     *
14228     * @return true if verification should be performed
14229     */
14230    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14231        if (!DEFAULT_VERIFY_ENABLE) {
14232            return false;
14233        }
14234
14235        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14236
14237        // Check if installing from ADB
14238        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14239            // Do not run verification in a test harness environment
14240            if (ActivityManager.isRunningInTestHarness()) {
14241                return false;
14242            }
14243            if (ensureVerifyAppsEnabled) {
14244                return true;
14245            }
14246            // Check if the developer does not want package verification for ADB installs
14247            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14248                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14249                return false;
14250            }
14251        } else {
14252            // only when not installed from ADB, skip verification for instant apps when
14253            // the installer and verifier are the same.
14254            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14255                if (mInstantAppInstallerActivity != null
14256                        && mInstantAppInstallerActivity.packageName.equals(
14257                                mRequiredVerifierPackage)) {
14258                    try {
14259                        mContext.getSystemService(AppOpsManager.class)
14260                                .checkPackage(installerUid, mRequiredVerifierPackage);
14261                        if (DEBUG_VERIFY) {
14262                            Slog.i(TAG, "disable verification for instant app");
14263                        }
14264                        return false;
14265                    } catch (SecurityException ignore) { }
14266                }
14267            }
14268        }
14269
14270        if (ensureVerifyAppsEnabled) {
14271            return true;
14272        }
14273
14274        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14275                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14276    }
14277
14278    @Override
14279    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14280            throws RemoteException {
14281        mContext.enforceCallingOrSelfPermission(
14282                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14283                "Only intentfilter verification agents can verify applications");
14284
14285        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14286        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14287                Binder.getCallingUid(), verificationCode, failedDomains);
14288        msg.arg1 = id;
14289        msg.obj = response;
14290        mHandler.sendMessage(msg);
14291    }
14292
14293    @Override
14294    public int getIntentVerificationStatus(String packageName, int userId) {
14295        final int callingUid = Binder.getCallingUid();
14296        if (UserHandle.getUserId(callingUid) != userId) {
14297            mContext.enforceCallingOrSelfPermission(
14298                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14299                    "getIntentVerificationStatus" + userId);
14300        }
14301        if (getInstantAppPackageName(callingUid) != null) {
14302            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14303        }
14304        synchronized (mPackages) {
14305            final PackageSetting ps = mSettings.mPackages.get(packageName);
14306            if (ps == null
14307                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14308                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14309            }
14310            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14311        }
14312    }
14313
14314    @Override
14315    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14316        mContext.enforceCallingOrSelfPermission(
14317                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14318
14319        boolean result = false;
14320        synchronized (mPackages) {
14321            final PackageSetting ps = mSettings.mPackages.get(packageName);
14322            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14323                return false;
14324            }
14325            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14326        }
14327        if (result) {
14328            scheduleWritePackageRestrictionsLocked(userId);
14329        }
14330        return result;
14331    }
14332
14333    @Override
14334    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14335            String packageName) {
14336        final int callingUid = Binder.getCallingUid();
14337        if (getInstantAppPackageName(callingUid) != null) {
14338            return ParceledListSlice.emptyList();
14339        }
14340        synchronized (mPackages) {
14341            final PackageSetting ps = mSettings.mPackages.get(packageName);
14342            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14343                return ParceledListSlice.emptyList();
14344            }
14345            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14346        }
14347    }
14348
14349    @Override
14350    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14351        if (TextUtils.isEmpty(packageName)) {
14352            return ParceledListSlice.emptyList();
14353        }
14354        final int callingUid = Binder.getCallingUid();
14355        final int callingUserId = UserHandle.getUserId(callingUid);
14356        synchronized (mPackages) {
14357            PackageParser.Package pkg = mPackages.get(packageName);
14358            if (pkg == null || pkg.activities == null) {
14359                return ParceledListSlice.emptyList();
14360            }
14361            if (pkg.mExtras == null) {
14362                return ParceledListSlice.emptyList();
14363            }
14364            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14365            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14366                return ParceledListSlice.emptyList();
14367            }
14368            final int count = pkg.activities.size();
14369            ArrayList<IntentFilter> result = new ArrayList<>();
14370            for (int n=0; n<count; n++) {
14371                PackageParser.Activity activity = pkg.activities.get(n);
14372                if (activity.intents != null && activity.intents.size() > 0) {
14373                    result.addAll(activity.intents);
14374                }
14375            }
14376            return new ParceledListSlice<>(result);
14377        }
14378    }
14379
14380    @Override
14381    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14382        mContext.enforceCallingOrSelfPermission(
14383                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14384        if (UserHandle.getCallingUserId() != userId) {
14385            mContext.enforceCallingOrSelfPermission(
14386                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14387        }
14388
14389        synchronized (mPackages) {
14390            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14391            if (packageName != null) {
14392                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14393                        packageName, userId);
14394            }
14395            return result;
14396        }
14397    }
14398
14399    @Override
14400    public String getDefaultBrowserPackageName(int userId) {
14401        if (UserHandle.getCallingUserId() != userId) {
14402            mContext.enforceCallingOrSelfPermission(
14403                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14404        }
14405        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14406            return null;
14407        }
14408        synchronized (mPackages) {
14409            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14410        }
14411    }
14412
14413    /**
14414     * Get the "allow unknown sources" setting.
14415     *
14416     * @return the current "allow unknown sources" setting
14417     */
14418    private int getUnknownSourcesSettings() {
14419        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14420                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14421                -1);
14422    }
14423
14424    @Override
14425    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14426        final int callingUid = Binder.getCallingUid();
14427        if (getInstantAppPackageName(callingUid) != null) {
14428            return;
14429        }
14430        // writer
14431        synchronized (mPackages) {
14432            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14433            if (targetPackageSetting == null
14434                    || filterAppAccessLPr(
14435                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14436                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14437            }
14438
14439            PackageSetting installerPackageSetting;
14440            if (installerPackageName != null) {
14441                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14442                if (installerPackageSetting == null) {
14443                    throw new IllegalArgumentException("Unknown installer package: "
14444                            + installerPackageName);
14445                }
14446            } else {
14447                installerPackageSetting = null;
14448            }
14449
14450            Signature[] callerSignature;
14451            Object obj = mSettings.getUserIdLPr(callingUid);
14452            if (obj != null) {
14453                if (obj instanceof SharedUserSetting) {
14454                    callerSignature =
14455                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14456                } else if (obj instanceof PackageSetting) {
14457                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14458                } else {
14459                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14460                }
14461            } else {
14462                throw new SecurityException("Unknown calling UID: " + callingUid);
14463            }
14464
14465            // Verify: can't set installerPackageName to a package that is
14466            // not signed with the same cert as the caller.
14467            if (installerPackageSetting != null) {
14468                if (compareSignatures(callerSignature,
14469                        installerPackageSetting.signatures.mSigningDetails.signatures)
14470                        != PackageManager.SIGNATURE_MATCH) {
14471                    throw new SecurityException(
14472                            "Caller does not have same cert as new installer package "
14473                            + installerPackageName);
14474                }
14475            }
14476
14477            // Verify: if target already has an installer package, it must
14478            // be signed with the same cert as the caller.
14479            if (targetPackageSetting.installerPackageName != null) {
14480                PackageSetting setting = mSettings.mPackages.get(
14481                        targetPackageSetting.installerPackageName);
14482                // If the currently set package isn't valid, then it's always
14483                // okay to change it.
14484                if (setting != null) {
14485                    if (compareSignatures(callerSignature,
14486                            setting.signatures.mSigningDetails.signatures)
14487                            != PackageManager.SIGNATURE_MATCH) {
14488                        throw new SecurityException(
14489                                "Caller does not have same cert as old installer package "
14490                                + targetPackageSetting.installerPackageName);
14491                    }
14492                }
14493            }
14494
14495            // Okay!
14496            targetPackageSetting.installerPackageName = installerPackageName;
14497            if (installerPackageName != null) {
14498                mSettings.mInstallerPackages.add(installerPackageName);
14499            }
14500            scheduleWriteSettingsLocked();
14501        }
14502    }
14503
14504    @Override
14505    public void setApplicationCategoryHint(String packageName, int categoryHint,
14506            String callerPackageName) {
14507        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14508            throw new SecurityException("Instant applications don't have access to this method");
14509        }
14510        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14511                callerPackageName);
14512        synchronized (mPackages) {
14513            PackageSetting ps = mSettings.mPackages.get(packageName);
14514            if (ps == null) {
14515                throw new IllegalArgumentException("Unknown target package " + packageName);
14516            }
14517            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14518                throw new IllegalArgumentException("Unknown target package " + packageName);
14519            }
14520            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14521                throw new IllegalArgumentException("Calling package " + callerPackageName
14522                        + " is not installer for " + packageName);
14523            }
14524
14525            if (ps.categoryHint != categoryHint) {
14526                ps.categoryHint = categoryHint;
14527                scheduleWriteSettingsLocked();
14528            }
14529        }
14530    }
14531
14532    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14533        // Queue up an async operation since the package installation may take a little while.
14534        mHandler.post(new Runnable() {
14535            public void run() {
14536                mHandler.removeCallbacks(this);
14537                 // Result object to be returned
14538                PackageInstalledInfo res = new PackageInstalledInfo();
14539                res.setReturnCode(currentStatus);
14540                res.uid = -1;
14541                res.pkg = null;
14542                res.removedInfo = null;
14543                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14544                    args.doPreInstall(res.returnCode);
14545                    synchronized (mInstallLock) {
14546                        installPackageTracedLI(args, res);
14547                    }
14548                    args.doPostInstall(res.returnCode, res.uid);
14549                }
14550
14551                // A restore should be performed at this point if (a) the install
14552                // succeeded, (b) the operation is not an update, and (c) the new
14553                // package has not opted out of backup participation.
14554                final boolean update = res.removedInfo != null
14555                        && res.removedInfo.removedPackage != null;
14556                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14557                boolean doRestore = !update
14558                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14559
14560                // Set up the post-install work request bookkeeping.  This will be used
14561                // and cleaned up by the post-install event handling regardless of whether
14562                // there's a restore pass performed.  Token values are >= 1.
14563                int token;
14564                if (mNextInstallToken < 0) mNextInstallToken = 1;
14565                token = mNextInstallToken++;
14566
14567                PostInstallData data = new PostInstallData(args, res);
14568                mRunningInstalls.put(token, data);
14569                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14570
14571                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14572                    // Pass responsibility to the Backup Manager.  It will perform a
14573                    // restore if appropriate, then pass responsibility back to the
14574                    // Package Manager to run the post-install observer callbacks
14575                    // and broadcasts.
14576                    IBackupManager bm = IBackupManager.Stub.asInterface(
14577                            ServiceManager.getService(Context.BACKUP_SERVICE));
14578                    if (bm != null) {
14579                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14580                                + " to BM for possible restore");
14581                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14582                        try {
14583                            // TODO: http://b/22388012
14584                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14585                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14586                            } else {
14587                                doRestore = false;
14588                            }
14589                        } catch (RemoteException e) {
14590                            // can't happen; the backup manager is local
14591                        } catch (Exception e) {
14592                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14593                            doRestore = false;
14594                        }
14595                    } else {
14596                        Slog.e(TAG, "Backup Manager not found!");
14597                        doRestore = false;
14598                    }
14599                }
14600
14601                if (!doRestore) {
14602                    // No restore possible, or the Backup Manager was mysteriously not
14603                    // available -- just fire the post-install work request directly.
14604                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14605
14606                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14607
14608                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14609                    mHandler.sendMessage(msg);
14610                }
14611            }
14612        });
14613    }
14614
14615    /**
14616     * Callback from PackageSettings whenever an app is first transitioned out of the
14617     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14618     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14619     * here whether the app is the target of an ongoing install, and only send the
14620     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14621     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14622     * handling.
14623     */
14624    void notifyFirstLaunch(final String packageName, final String installerPackage,
14625            final int userId) {
14626        // Serialize this with the rest of the install-process message chain.  In the
14627        // restore-at-install case, this Runnable will necessarily run before the
14628        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14629        // are coherent.  In the non-restore case, the app has already completed install
14630        // and been launched through some other means, so it is not in a problematic
14631        // state for observers to see the FIRST_LAUNCH signal.
14632        mHandler.post(new Runnable() {
14633            @Override
14634            public void run() {
14635                for (int i = 0; i < mRunningInstalls.size(); i++) {
14636                    final PostInstallData data = mRunningInstalls.valueAt(i);
14637                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14638                        continue;
14639                    }
14640                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14641                        // right package; but is it for the right user?
14642                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14643                            if (userId == data.res.newUsers[uIndex]) {
14644                                if (DEBUG_BACKUP) {
14645                                    Slog.i(TAG, "Package " + packageName
14646                                            + " being restored so deferring FIRST_LAUNCH");
14647                                }
14648                                return;
14649                            }
14650                        }
14651                    }
14652                }
14653                // didn't find it, so not being restored
14654                if (DEBUG_BACKUP) {
14655                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14656                }
14657                final boolean isInstantApp = isInstantApp(packageName, userId);
14658                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14659                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14660                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14661            }
14662        });
14663    }
14664
14665    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14666            int[] userIds, int[] instantUserIds) {
14667        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14668                installerPkg, null, userIds, instantUserIds);
14669    }
14670
14671    private abstract class HandlerParams {
14672        private static final int MAX_RETRIES = 4;
14673
14674        /**
14675         * Number of times startCopy() has been attempted and had a non-fatal
14676         * error.
14677         */
14678        private int mRetries = 0;
14679
14680        /** User handle for the user requesting the information or installation. */
14681        private final UserHandle mUser;
14682        String traceMethod;
14683        int traceCookie;
14684
14685        HandlerParams(UserHandle user) {
14686            mUser = user;
14687        }
14688
14689        UserHandle getUser() {
14690            return mUser;
14691        }
14692
14693        HandlerParams setTraceMethod(String traceMethod) {
14694            this.traceMethod = traceMethod;
14695            return this;
14696        }
14697
14698        HandlerParams setTraceCookie(int traceCookie) {
14699            this.traceCookie = traceCookie;
14700            return this;
14701        }
14702
14703        final boolean startCopy() {
14704            boolean res;
14705            try {
14706                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14707
14708                if (++mRetries > MAX_RETRIES) {
14709                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14710                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14711                    handleServiceError();
14712                    return false;
14713                } else {
14714                    handleStartCopy();
14715                    res = true;
14716                }
14717            } catch (RemoteException e) {
14718                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14719                mHandler.sendEmptyMessage(MCS_RECONNECT);
14720                res = false;
14721            }
14722            handleReturnCode();
14723            return res;
14724        }
14725
14726        final void serviceError() {
14727            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14728            handleServiceError();
14729            handleReturnCode();
14730        }
14731
14732        abstract void handleStartCopy() throws RemoteException;
14733        abstract void handleServiceError();
14734        abstract void handleReturnCode();
14735    }
14736
14737    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14738        for (File path : paths) {
14739            try {
14740                mcs.clearDirectory(path.getAbsolutePath());
14741            } catch (RemoteException e) {
14742            }
14743        }
14744    }
14745
14746    static class OriginInfo {
14747        /**
14748         * Location where install is coming from, before it has been
14749         * copied/renamed into place. This could be a single monolithic APK
14750         * file, or a cluster directory. This location may be untrusted.
14751         */
14752        final File file;
14753
14754        /**
14755         * Flag indicating that {@link #file} or {@link #cid} has already been
14756         * staged, meaning downstream users don't need to defensively copy the
14757         * contents.
14758         */
14759        final boolean staged;
14760
14761        /**
14762         * Flag indicating that {@link #file} or {@link #cid} is an already
14763         * installed app that is being moved.
14764         */
14765        final boolean existing;
14766
14767        final String resolvedPath;
14768        final File resolvedFile;
14769
14770        static OriginInfo fromNothing() {
14771            return new OriginInfo(null, false, false);
14772        }
14773
14774        static OriginInfo fromUntrustedFile(File file) {
14775            return new OriginInfo(file, false, false);
14776        }
14777
14778        static OriginInfo fromExistingFile(File file) {
14779            return new OriginInfo(file, false, true);
14780        }
14781
14782        static OriginInfo fromStagedFile(File file) {
14783            return new OriginInfo(file, true, false);
14784        }
14785
14786        private OriginInfo(File file, boolean staged, boolean existing) {
14787            this.file = file;
14788            this.staged = staged;
14789            this.existing = existing;
14790
14791            if (file != null) {
14792                resolvedPath = file.getAbsolutePath();
14793                resolvedFile = file;
14794            } else {
14795                resolvedPath = null;
14796                resolvedFile = null;
14797            }
14798        }
14799    }
14800
14801    static class MoveInfo {
14802        final int moveId;
14803        final String fromUuid;
14804        final String toUuid;
14805        final String packageName;
14806        final String dataAppName;
14807        final int appId;
14808        final String seinfo;
14809        final int targetSdkVersion;
14810
14811        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14812                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14813            this.moveId = moveId;
14814            this.fromUuid = fromUuid;
14815            this.toUuid = toUuid;
14816            this.packageName = packageName;
14817            this.dataAppName = dataAppName;
14818            this.appId = appId;
14819            this.seinfo = seinfo;
14820            this.targetSdkVersion = targetSdkVersion;
14821        }
14822    }
14823
14824    static class VerificationInfo {
14825        /** A constant used to indicate that a uid value is not present. */
14826        public static final int NO_UID = -1;
14827
14828        /** URI referencing where the package was downloaded from. */
14829        final Uri originatingUri;
14830
14831        /** HTTP referrer URI associated with the originatingURI. */
14832        final Uri referrer;
14833
14834        /** UID of the application that the install request originated from. */
14835        final int originatingUid;
14836
14837        /** UID of application requesting the install */
14838        final int installerUid;
14839
14840        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14841            this.originatingUri = originatingUri;
14842            this.referrer = referrer;
14843            this.originatingUid = originatingUid;
14844            this.installerUid = installerUid;
14845        }
14846    }
14847
14848    class InstallParams extends HandlerParams {
14849        final OriginInfo origin;
14850        final MoveInfo move;
14851        final IPackageInstallObserver2 observer;
14852        int installFlags;
14853        final String installerPackageName;
14854        final String volumeUuid;
14855        private InstallArgs mArgs;
14856        private int mRet;
14857        final String packageAbiOverride;
14858        final String[] grantedRuntimePermissions;
14859        final VerificationInfo verificationInfo;
14860        final PackageParser.SigningDetails signingDetails;
14861        final int installReason;
14862
14863        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14864                int installFlags, String installerPackageName, String volumeUuid,
14865                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14866                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14867            super(user);
14868            this.origin = origin;
14869            this.move = move;
14870            this.observer = observer;
14871            this.installFlags = installFlags;
14872            this.installerPackageName = installerPackageName;
14873            this.volumeUuid = volumeUuid;
14874            this.verificationInfo = verificationInfo;
14875            this.packageAbiOverride = packageAbiOverride;
14876            this.grantedRuntimePermissions = grantedPermissions;
14877            this.signingDetails = signingDetails;
14878            this.installReason = installReason;
14879        }
14880
14881        @Override
14882        public String toString() {
14883            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14884                    + " file=" + origin.file + "}";
14885        }
14886
14887        private int installLocationPolicy(PackageInfoLite pkgLite) {
14888            String packageName = pkgLite.packageName;
14889            int installLocation = pkgLite.installLocation;
14890            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14891            // reader
14892            synchronized (mPackages) {
14893                // Currently installed package which the new package is attempting to replace or
14894                // null if no such package is installed.
14895                PackageParser.Package installedPkg = mPackages.get(packageName);
14896                // Package which currently owns the data which the new package will own if installed.
14897                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14898                // will be null whereas dataOwnerPkg will contain information about the package
14899                // which was uninstalled while keeping its data.
14900                PackageParser.Package dataOwnerPkg = installedPkg;
14901                if (dataOwnerPkg  == null) {
14902                    PackageSetting ps = mSettings.mPackages.get(packageName);
14903                    if (ps != null) {
14904                        dataOwnerPkg = ps.pkg;
14905                    }
14906                }
14907
14908                if (dataOwnerPkg != null) {
14909                    // If installed, the package will get access to data left on the device by its
14910                    // predecessor. As a security measure, this is permited only if this is not a
14911                    // version downgrade or if the predecessor package is marked as debuggable and
14912                    // a downgrade is explicitly requested.
14913                    //
14914                    // On debuggable platform builds, downgrades are permitted even for
14915                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14916                    // not offer security guarantees and thus it's OK to disable some security
14917                    // mechanisms to make debugging/testing easier on those builds. However, even on
14918                    // debuggable builds downgrades of packages are permitted only if requested via
14919                    // installFlags. This is because we aim to keep the behavior of debuggable
14920                    // platform builds as close as possible to the behavior of non-debuggable
14921                    // platform builds.
14922                    final boolean downgradeRequested =
14923                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14924                    final boolean packageDebuggable =
14925                                (dataOwnerPkg.applicationInfo.flags
14926                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14927                    final boolean downgradePermitted =
14928                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14929                    if (!downgradePermitted) {
14930                        try {
14931                            checkDowngrade(dataOwnerPkg, pkgLite);
14932                        } catch (PackageManagerException e) {
14933                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14934                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14935                        }
14936                    }
14937                }
14938
14939                if (installedPkg != null) {
14940                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14941                        // Check for updated system application.
14942                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14943                            if (onSd) {
14944                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14945                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14946                            }
14947                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14948                        } else {
14949                            if (onSd) {
14950                                // Install flag overrides everything.
14951                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14952                            }
14953                            // If current upgrade specifies particular preference
14954                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14955                                // Application explicitly specified internal.
14956                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14957                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14958                                // App explictly prefers external. Let policy decide
14959                            } else {
14960                                // Prefer previous location
14961                                if (isExternal(installedPkg)) {
14962                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14963                                }
14964                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14965                            }
14966                        }
14967                    } else {
14968                        // Invalid install. Return error code
14969                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14970                    }
14971                }
14972            }
14973            // All the special cases have been taken care of.
14974            // Return result based on recommended install location.
14975            if (onSd) {
14976                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14977            }
14978            return pkgLite.recommendedInstallLocation;
14979        }
14980
14981        /*
14982         * Invoke remote method to get package information and install
14983         * location values. Override install location based on default
14984         * policy if needed and then create install arguments based
14985         * on the install location.
14986         */
14987        public void handleStartCopy() throws RemoteException {
14988            int ret = PackageManager.INSTALL_SUCCEEDED;
14989
14990            // If we're already staged, we've firmly committed to an install location
14991            if (origin.staged) {
14992                if (origin.file != null) {
14993                    installFlags |= PackageManager.INSTALL_INTERNAL;
14994                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14995                } else {
14996                    throw new IllegalStateException("Invalid stage location");
14997                }
14998            }
14999
15000            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15001            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15002            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15003            PackageInfoLite pkgLite = null;
15004
15005            if (onInt && onSd) {
15006                // Check if both bits are set.
15007                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15008                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15009            } else if (onSd && ephemeral) {
15010                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15011                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15012            } else {
15013                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15014                        packageAbiOverride);
15015
15016                if (DEBUG_INSTANT && ephemeral) {
15017                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15018                }
15019
15020                /*
15021                 * If we have too little free space, try to free cache
15022                 * before giving up.
15023                 */
15024                if (!origin.staged && pkgLite.recommendedInstallLocation
15025                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15026                    // TODO: focus freeing disk space on the target device
15027                    final StorageManager storage = StorageManager.from(mContext);
15028                    final long lowThreshold = storage.getStorageLowBytes(
15029                            Environment.getDataDirectory());
15030
15031                    final long sizeBytes = mContainerService.calculateInstalledSize(
15032                            origin.resolvedPath, packageAbiOverride);
15033
15034                    try {
15035                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15036                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15037                                installFlags, packageAbiOverride);
15038                    } catch (InstallerException e) {
15039                        Slog.w(TAG, "Failed to free cache", e);
15040                    }
15041
15042                    /*
15043                     * The cache free must have deleted the file we
15044                     * downloaded to install.
15045                     *
15046                     * TODO: fix the "freeCache" call to not delete
15047                     *       the file we care about.
15048                     */
15049                    if (pkgLite.recommendedInstallLocation
15050                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15051                        pkgLite.recommendedInstallLocation
15052                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15053                    }
15054                }
15055            }
15056
15057            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15058                int loc = pkgLite.recommendedInstallLocation;
15059                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15060                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15061                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15062                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15063                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15064                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15065                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15066                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15067                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15068                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15069                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15070                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15071                } else {
15072                    // Override with defaults if needed.
15073                    loc = installLocationPolicy(pkgLite);
15074                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15075                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15076                    } else if (!onSd && !onInt) {
15077                        // Override install location with flags
15078                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15079                            // Set the flag to install on external media.
15080                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15081                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15082                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15083                            if (DEBUG_INSTANT) {
15084                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15085                            }
15086                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15087                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15088                                    |PackageManager.INSTALL_INTERNAL);
15089                        } else {
15090                            // Make sure the flag for installing on external
15091                            // media is unset
15092                            installFlags |= PackageManager.INSTALL_INTERNAL;
15093                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15094                        }
15095                    }
15096                }
15097            }
15098
15099            final InstallArgs args = createInstallArgs(this);
15100            mArgs = args;
15101
15102            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15103                // TODO: http://b/22976637
15104                // Apps installed for "all" users use the device owner to verify the app
15105                UserHandle verifierUser = getUser();
15106                if (verifierUser == UserHandle.ALL) {
15107                    verifierUser = UserHandle.SYSTEM;
15108                }
15109
15110                /*
15111                 * Determine if we have any installed package verifiers. If we
15112                 * do, then we'll defer to them to verify the packages.
15113                 */
15114                final int requiredUid = mRequiredVerifierPackage == null ? -1
15115                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15116                                verifierUser.getIdentifier());
15117                final int installerUid =
15118                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15119                if (!origin.existing && requiredUid != -1
15120                        && isVerificationEnabled(
15121                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15122                    final Intent verification = new Intent(
15123                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15124                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15125                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15126                            PACKAGE_MIME_TYPE);
15127                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15128
15129                    // Query all live verifiers based on current user state
15130                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15131                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15132                            false /*allowDynamicSplits*/);
15133
15134                    if (DEBUG_VERIFY) {
15135                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15136                                + verification.toString() + " with " + pkgLite.verifiers.length
15137                                + " optional verifiers");
15138                    }
15139
15140                    final int verificationId = mPendingVerificationToken++;
15141
15142                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15143
15144                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15145                            installerPackageName);
15146
15147                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15148                            installFlags);
15149
15150                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15151                            pkgLite.packageName);
15152
15153                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15154                            pkgLite.versionCode);
15155
15156                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15157                            pkgLite.getLongVersionCode());
15158
15159                    if (verificationInfo != null) {
15160                        if (verificationInfo.originatingUri != null) {
15161                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15162                                    verificationInfo.originatingUri);
15163                        }
15164                        if (verificationInfo.referrer != null) {
15165                            verification.putExtra(Intent.EXTRA_REFERRER,
15166                                    verificationInfo.referrer);
15167                        }
15168                        if (verificationInfo.originatingUid >= 0) {
15169                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15170                                    verificationInfo.originatingUid);
15171                        }
15172                        if (verificationInfo.installerUid >= 0) {
15173                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15174                                    verificationInfo.installerUid);
15175                        }
15176                    }
15177
15178                    final PackageVerificationState verificationState = new PackageVerificationState(
15179                            requiredUid, args);
15180
15181                    mPendingVerification.append(verificationId, verificationState);
15182
15183                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15184                            receivers, verificationState);
15185
15186                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15187                    final long idleDuration = getVerificationTimeout();
15188
15189                    /*
15190                     * If any sufficient verifiers were listed in the package
15191                     * manifest, attempt to ask them.
15192                     */
15193                    if (sufficientVerifiers != null) {
15194                        final int N = sufficientVerifiers.size();
15195                        if (N == 0) {
15196                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15197                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15198                        } else {
15199                            for (int i = 0; i < N; i++) {
15200                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15201                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15202                                        verifierComponent.getPackageName(), idleDuration,
15203                                        verifierUser.getIdentifier(), false, "package verifier");
15204
15205                                final Intent sufficientIntent = new Intent(verification);
15206                                sufficientIntent.setComponent(verifierComponent);
15207                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15208                            }
15209                        }
15210                    }
15211
15212                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15213                            mRequiredVerifierPackage, receivers);
15214                    if (ret == PackageManager.INSTALL_SUCCEEDED
15215                            && mRequiredVerifierPackage != null) {
15216                        Trace.asyncTraceBegin(
15217                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15218                        /*
15219                         * Send the intent to the required verification agent,
15220                         * but only start the verification timeout after the
15221                         * target BroadcastReceivers have run.
15222                         */
15223                        verification.setComponent(requiredVerifierComponent);
15224                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15225                                mRequiredVerifierPackage, idleDuration,
15226                                verifierUser.getIdentifier(), false, "package verifier");
15227                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15228                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15229                                new BroadcastReceiver() {
15230                                    @Override
15231                                    public void onReceive(Context context, Intent intent) {
15232                                        final Message msg = mHandler
15233                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15234                                        msg.arg1 = verificationId;
15235                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15236                                    }
15237                                }, null, 0, null, null);
15238
15239                        /*
15240                         * We don't want the copy to proceed until verification
15241                         * succeeds, so null out this field.
15242                         */
15243                        mArgs = null;
15244                    }
15245                } else {
15246                    /*
15247                     * No package verification is enabled, so immediately start
15248                     * the remote call to initiate copy using temporary file.
15249                     */
15250                    ret = args.copyApk(mContainerService, true);
15251                }
15252            }
15253
15254            mRet = ret;
15255        }
15256
15257        @Override
15258        void handleReturnCode() {
15259            // If mArgs is null, then MCS couldn't be reached. When it
15260            // reconnects, it will try again to install. At that point, this
15261            // will succeed.
15262            if (mArgs != null) {
15263                processPendingInstall(mArgs, mRet);
15264            }
15265        }
15266
15267        @Override
15268        void handleServiceError() {
15269            mArgs = createInstallArgs(this);
15270            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15271        }
15272    }
15273
15274    private InstallArgs createInstallArgs(InstallParams params) {
15275        if (params.move != null) {
15276            return new MoveInstallArgs(params);
15277        } else {
15278            return new FileInstallArgs(params);
15279        }
15280    }
15281
15282    /**
15283     * Create args that describe an existing installed package. Typically used
15284     * when cleaning up old installs, or used as a move source.
15285     */
15286    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15287            String resourcePath, String[] instructionSets) {
15288        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15289    }
15290
15291    static abstract class InstallArgs {
15292        /** @see InstallParams#origin */
15293        final OriginInfo origin;
15294        /** @see InstallParams#move */
15295        final MoveInfo move;
15296
15297        final IPackageInstallObserver2 observer;
15298        // Always refers to PackageManager flags only
15299        final int installFlags;
15300        final String installerPackageName;
15301        final String volumeUuid;
15302        final UserHandle user;
15303        final String abiOverride;
15304        final String[] installGrantPermissions;
15305        /** If non-null, drop an async trace when the install completes */
15306        final String traceMethod;
15307        final int traceCookie;
15308        final PackageParser.SigningDetails signingDetails;
15309        final int installReason;
15310
15311        // The list of instruction sets supported by this app. This is currently
15312        // only used during the rmdex() phase to clean up resources. We can get rid of this
15313        // if we move dex files under the common app path.
15314        /* nullable */ String[] instructionSets;
15315
15316        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15317                int installFlags, String installerPackageName, String volumeUuid,
15318                UserHandle user, String[] instructionSets,
15319                String abiOverride, String[] installGrantPermissions,
15320                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15321                int installReason) {
15322            this.origin = origin;
15323            this.move = move;
15324            this.installFlags = installFlags;
15325            this.observer = observer;
15326            this.installerPackageName = installerPackageName;
15327            this.volumeUuid = volumeUuid;
15328            this.user = user;
15329            this.instructionSets = instructionSets;
15330            this.abiOverride = abiOverride;
15331            this.installGrantPermissions = installGrantPermissions;
15332            this.traceMethod = traceMethod;
15333            this.traceCookie = traceCookie;
15334            this.signingDetails = signingDetails;
15335            this.installReason = installReason;
15336        }
15337
15338        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15339        abstract int doPreInstall(int status);
15340
15341        /**
15342         * Rename package into final resting place. All paths on the given
15343         * scanned package should be updated to reflect the rename.
15344         */
15345        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15346        abstract int doPostInstall(int status, int uid);
15347
15348        /** @see PackageSettingBase#codePathString */
15349        abstract String getCodePath();
15350        /** @see PackageSettingBase#resourcePathString */
15351        abstract String getResourcePath();
15352
15353        // Need installer lock especially for dex file removal.
15354        abstract void cleanUpResourcesLI();
15355        abstract boolean doPostDeleteLI(boolean delete);
15356
15357        /**
15358         * Called before the source arguments are copied. This is used mostly
15359         * for MoveParams when it needs to read the source file to put it in the
15360         * destination.
15361         */
15362        int doPreCopy() {
15363            return PackageManager.INSTALL_SUCCEEDED;
15364        }
15365
15366        /**
15367         * Called after the source arguments are copied. This is used mostly for
15368         * MoveParams when it needs to read the source file to put it in the
15369         * destination.
15370         */
15371        int doPostCopy(int uid) {
15372            return PackageManager.INSTALL_SUCCEEDED;
15373        }
15374
15375        protected boolean isFwdLocked() {
15376            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15377        }
15378
15379        protected boolean isExternalAsec() {
15380            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15381        }
15382
15383        protected boolean isEphemeral() {
15384            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15385        }
15386
15387        UserHandle getUser() {
15388            return user;
15389        }
15390    }
15391
15392    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15393        if (!allCodePaths.isEmpty()) {
15394            if (instructionSets == null) {
15395                throw new IllegalStateException("instructionSet == null");
15396            }
15397            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15398            for (String codePath : allCodePaths) {
15399                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15400                    try {
15401                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15402                    } catch (InstallerException ignored) {
15403                    }
15404                }
15405            }
15406        }
15407    }
15408
15409    /**
15410     * Logic to handle installation of non-ASEC applications, including copying
15411     * and renaming logic.
15412     */
15413    class FileInstallArgs extends InstallArgs {
15414        private File codeFile;
15415        private File resourceFile;
15416
15417        // Example topology:
15418        // /data/app/com.example/base.apk
15419        // /data/app/com.example/split_foo.apk
15420        // /data/app/com.example/lib/arm/libfoo.so
15421        // /data/app/com.example/lib/arm64/libfoo.so
15422        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15423
15424        /** New install */
15425        FileInstallArgs(InstallParams params) {
15426            super(params.origin, params.move, params.observer, params.installFlags,
15427                    params.installerPackageName, params.volumeUuid,
15428                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15429                    params.grantedRuntimePermissions,
15430                    params.traceMethod, params.traceCookie, params.signingDetails,
15431                    params.installReason);
15432            if (isFwdLocked()) {
15433                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15434            }
15435        }
15436
15437        /** Existing install */
15438        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15439            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15440                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15441                    PackageManager.INSTALL_REASON_UNKNOWN);
15442            this.codeFile = (codePath != null) ? new File(codePath) : null;
15443            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15444        }
15445
15446        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15447            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15448            try {
15449                return doCopyApk(imcs, temp);
15450            } finally {
15451                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15452            }
15453        }
15454
15455        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15456            if (origin.staged) {
15457                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15458                codeFile = origin.file;
15459                resourceFile = origin.file;
15460                return PackageManager.INSTALL_SUCCEEDED;
15461            }
15462
15463            try {
15464                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15465                final File tempDir =
15466                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15467                codeFile = tempDir;
15468                resourceFile = tempDir;
15469            } catch (IOException e) {
15470                Slog.w(TAG, "Failed to create copy file: " + e);
15471                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15472            }
15473
15474            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15475                @Override
15476                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15477                    if (!FileUtils.isValidExtFilename(name)) {
15478                        throw new IllegalArgumentException("Invalid filename: " + name);
15479                    }
15480                    try {
15481                        final File file = new File(codeFile, name);
15482                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15483                                O_RDWR | O_CREAT, 0644);
15484                        Os.chmod(file.getAbsolutePath(), 0644);
15485                        return new ParcelFileDescriptor(fd);
15486                    } catch (ErrnoException e) {
15487                        throw new RemoteException("Failed to open: " + e.getMessage());
15488                    }
15489                }
15490            };
15491
15492            int ret = PackageManager.INSTALL_SUCCEEDED;
15493            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15494            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15495                Slog.e(TAG, "Failed to copy package");
15496                return ret;
15497            }
15498
15499            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15500            NativeLibraryHelper.Handle handle = null;
15501            try {
15502                handle = NativeLibraryHelper.Handle.create(codeFile);
15503                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15504                        abiOverride);
15505            } catch (IOException e) {
15506                Slog.e(TAG, "Copying native libraries failed", e);
15507                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15508            } finally {
15509                IoUtils.closeQuietly(handle);
15510            }
15511
15512            return ret;
15513        }
15514
15515        int doPreInstall(int status) {
15516            if (status != PackageManager.INSTALL_SUCCEEDED) {
15517                cleanUp();
15518            }
15519            return status;
15520        }
15521
15522        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15523            if (status != PackageManager.INSTALL_SUCCEEDED) {
15524                cleanUp();
15525                return false;
15526            }
15527
15528            final File targetDir = codeFile.getParentFile();
15529            final File beforeCodeFile = codeFile;
15530            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15531
15532            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15533            try {
15534                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15535            } catch (ErrnoException e) {
15536                Slog.w(TAG, "Failed to rename", e);
15537                return false;
15538            }
15539
15540            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15541                Slog.w(TAG, "Failed to restorecon");
15542                return false;
15543            }
15544
15545            // Reflect the rename internally
15546            codeFile = afterCodeFile;
15547            resourceFile = afterCodeFile;
15548
15549            // Reflect the rename in scanned details
15550            try {
15551                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15552            } catch (IOException e) {
15553                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15554                return false;
15555            }
15556            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15557                    afterCodeFile, pkg.baseCodePath));
15558            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15559                    afterCodeFile, pkg.splitCodePaths));
15560
15561            // Reflect the rename in app info
15562            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15563            pkg.setApplicationInfoCodePath(pkg.codePath);
15564            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15565            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15566            pkg.setApplicationInfoResourcePath(pkg.codePath);
15567            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15568            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15569
15570            return true;
15571        }
15572
15573        int doPostInstall(int status, int uid) {
15574            if (status != PackageManager.INSTALL_SUCCEEDED) {
15575                cleanUp();
15576            }
15577            return status;
15578        }
15579
15580        @Override
15581        String getCodePath() {
15582            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15583        }
15584
15585        @Override
15586        String getResourcePath() {
15587            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15588        }
15589
15590        private boolean cleanUp() {
15591            if (codeFile == null || !codeFile.exists()) {
15592                return false;
15593            }
15594
15595            removeCodePathLI(codeFile);
15596
15597            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15598                resourceFile.delete();
15599            }
15600
15601            return true;
15602        }
15603
15604        void cleanUpResourcesLI() {
15605            // Try enumerating all code paths before deleting
15606            List<String> allCodePaths = Collections.EMPTY_LIST;
15607            if (codeFile != null && codeFile.exists()) {
15608                try {
15609                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15610                    allCodePaths = pkg.getAllCodePaths();
15611                } catch (PackageParserException e) {
15612                    // Ignored; we tried our best
15613                }
15614            }
15615
15616            cleanUp();
15617            removeDexFiles(allCodePaths, instructionSets);
15618        }
15619
15620        boolean doPostDeleteLI(boolean delete) {
15621            // XXX err, shouldn't we respect the delete flag?
15622            cleanUpResourcesLI();
15623            return true;
15624        }
15625    }
15626
15627    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15628            PackageManagerException {
15629        if (copyRet < 0) {
15630            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15631                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15632                throw new PackageManagerException(copyRet, message);
15633            }
15634        }
15635    }
15636
15637    /**
15638     * Extract the StorageManagerService "container ID" from the full code path of an
15639     * .apk.
15640     */
15641    static String cidFromCodePath(String fullCodePath) {
15642        int eidx = fullCodePath.lastIndexOf("/");
15643        String subStr1 = fullCodePath.substring(0, eidx);
15644        int sidx = subStr1.lastIndexOf("/");
15645        return subStr1.substring(sidx+1, eidx);
15646    }
15647
15648    /**
15649     * Logic to handle movement of existing installed applications.
15650     */
15651    class MoveInstallArgs extends InstallArgs {
15652        private File codeFile;
15653        private File resourceFile;
15654
15655        /** New install */
15656        MoveInstallArgs(InstallParams params) {
15657            super(params.origin, params.move, params.observer, params.installFlags,
15658                    params.installerPackageName, params.volumeUuid,
15659                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15660                    params.grantedRuntimePermissions,
15661                    params.traceMethod, params.traceCookie, params.signingDetails,
15662                    params.installReason);
15663        }
15664
15665        int copyApk(IMediaContainerService imcs, boolean temp) {
15666            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15667                    + move.fromUuid + " to " + move.toUuid);
15668            synchronized (mInstaller) {
15669                try {
15670                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15671                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15672                } catch (InstallerException e) {
15673                    Slog.w(TAG, "Failed to move app", e);
15674                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15675                }
15676            }
15677
15678            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15679            resourceFile = codeFile;
15680            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15681
15682            return PackageManager.INSTALL_SUCCEEDED;
15683        }
15684
15685        int doPreInstall(int status) {
15686            if (status != PackageManager.INSTALL_SUCCEEDED) {
15687                cleanUp(move.toUuid);
15688            }
15689            return status;
15690        }
15691
15692        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15693            if (status != PackageManager.INSTALL_SUCCEEDED) {
15694                cleanUp(move.toUuid);
15695                return false;
15696            }
15697
15698            // Reflect the move in app info
15699            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15700            pkg.setApplicationInfoCodePath(pkg.codePath);
15701            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15702            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15703            pkg.setApplicationInfoResourcePath(pkg.codePath);
15704            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15705            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15706
15707            return true;
15708        }
15709
15710        int doPostInstall(int status, int uid) {
15711            if (status == PackageManager.INSTALL_SUCCEEDED) {
15712                cleanUp(move.fromUuid);
15713            } else {
15714                cleanUp(move.toUuid);
15715            }
15716            return status;
15717        }
15718
15719        @Override
15720        String getCodePath() {
15721            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15722        }
15723
15724        @Override
15725        String getResourcePath() {
15726            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15727        }
15728
15729        private boolean cleanUp(String volumeUuid) {
15730            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15731                    move.dataAppName);
15732            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15733            final int[] userIds = sUserManager.getUserIds();
15734            synchronized (mInstallLock) {
15735                // Clean up both app data and code
15736                // All package moves are frozen until finished
15737                for (int userId : userIds) {
15738                    try {
15739                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15740                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15741                    } catch (InstallerException e) {
15742                        Slog.w(TAG, String.valueOf(e));
15743                    }
15744                }
15745                removeCodePathLI(codeFile);
15746            }
15747            return true;
15748        }
15749
15750        void cleanUpResourcesLI() {
15751            throw new UnsupportedOperationException();
15752        }
15753
15754        boolean doPostDeleteLI(boolean delete) {
15755            throw new UnsupportedOperationException();
15756        }
15757    }
15758
15759    static String getAsecPackageName(String packageCid) {
15760        int idx = packageCid.lastIndexOf("-");
15761        if (idx == -1) {
15762            return packageCid;
15763        }
15764        return packageCid.substring(0, idx);
15765    }
15766
15767    // Utility method used to create code paths based on package name and available index.
15768    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15769        String idxStr = "";
15770        int idx = 1;
15771        // Fall back to default value of idx=1 if prefix is not
15772        // part of oldCodePath
15773        if (oldCodePath != null) {
15774            String subStr = oldCodePath;
15775            // Drop the suffix right away
15776            if (suffix != null && subStr.endsWith(suffix)) {
15777                subStr = subStr.substring(0, subStr.length() - suffix.length());
15778            }
15779            // If oldCodePath already contains prefix find out the
15780            // ending index to either increment or decrement.
15781            int sidx = subStr.lastIndexOf(prefix);
15782            if (sidx != -1) {
15783                subStr = subStr.substring(sidx + prefix.length());
15784                if (subStr != null) {
15785                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15786                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15787                    }
15788                    try {
15789                        idx = Integer.parseInt(subStr);
15790                        if (idx <= 1) {
15791                            idx++;
15792                        } else {
15793                            idx--;
15794                        }
15795                    } catch(NumberFormatException e) {
15796                    }
15797                }
15798            }
15799        }
15800        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15801        return prefix + idxStr;
15802    }
15803
15804    private File getNextCodePath(File targetDir, String packageName) {
15805        File result;
15806        SecureRandom random = new SecureRandom();
15807        byte[] bytes = new byte[16];
15808        do {
15809            random.nextBytes(bytes);
15810            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15811            result = new File(targetDir, packageName + "-" + suffix);
15812        } while (result.exists());
15813        return result;
15814    }
15815
15816    // Utility method that returns the relative package path with respect
15817    // to the installation directory. Like say for /data/data/com.test-1.apk
15818    // string com.test-1 is returned.
15819    static String deriveCodePathName(String codePath) {
15820        if (codePath == null) {
15821            return null;
15822        }
15823        final File codeFile = new File(codePath);
15824        final String name = codeFile.getName();
15825        if (codeFile.isDirectory()) {
15826            return name;
15827        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15828            final int lastDot = name.lastIndexOf('.');
15829            return name.substring(0, lastDot);
15830        } else {
15831            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15832            return null;
15833        }
15834    }
15835
15836    static class PackageInstalledInfo {
15837        String name;
15838        int uid;
15839        // The set of users that originally had this package installed.
15840        int[] origUsers;
15841        // The set of users that now have this package installed.
15842        int[] newUsers;
15843        PackageParser.Package pkg;
15844        int returnCode;
15845        String returnMsg;
15846        String installerPackageName;
15847        PackageRemovedInfo removedInfo;
15848        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15849
15850        public void setError(int code, String msg) {
15851            setReturnCode(code);
15852            setReturnMessage(msg);
15853            Slog.w(TAG, msg);
15854        }
15855
15856        public void setError(String msg, PackageParserException e) {
15857            setReturnCode(e.error);
15858            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15859            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15860            for (int i = 0; i < childCount; i++) {
15861                addedChildPackages.valueAt(i).setError(msg, e);
15862            }
15863            Slog.w(TAG, msg, e);
15864        }
15865
15866        public void setError(String msg, PackageManagerException e) {
15867            returnCode = e.error;
15868            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15869            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15870            for (int i = 0; i < childCount; i++) {
15871                addedChildPackages.valueAt(i).setError(msg, e);
15872            }
15873            Slog.w(TAG, msg, e);
15874        }
15875
15876        public void setReturnCode(int returnCode) {
15877            this.returnCode = returnCode;
15878            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15879            for (int i = 0; i < childCount; i++) {
15880                addedChildPackages.valueAt(i).returnCode = returnCode;
15881            }
15882        }
15883
15884        private void setReturnMessage(String returnMsg) {
15885            this.returnMsg = returnMsg;
15886            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15887            for (int i = 0; i < childCount; i++) {
15888                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15889            }
15890        }
15891
15892        // In some error cases we want to convey more info back to the observer
15893        String origPackage;
15894        String origPermission;
15895    }
15896
15897    /*
15898     * Install a non-existing package.
15899     */
15900    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15901            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15902            String volumeUuid, PackageInstalledInfo res, int installReason) {
15903        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15904
15905        // Remember this for later, in case we need to rollback this install
15906        String pkgName = pkg.packageName;
15907
15908        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15909
15910        synchronized(mPackages) {
15911            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15912            if (renamedPackage != null) {
15913                // A package with the same name is already installed, though
15914                // it has been renamed to an older name.  The package we
15915                // are trying to install should be installed as an update to
15916                // the existing one, but that has not been requested, so bail.
15917                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15918                        + " without first uninstalling package running as "
15919                        + renamedPackage);
15920                return;
15921            }
15922            if (mPackages.containsKey(pkgName)) {
15923                // Don't allow installation over an existing package with the same name.
15924                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15925                        + " without first uninstalling.");
15926                return;
15927            }
15928        }
15929
15930        try {
15931            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15932                    System.currentTimeMillis(), user);
15933
15934            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15935
15936            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15937                prepareAppDataAfterInstallLIF(newPackage);
15938
15939            } else {
15940                // Remove package from internal structures, but keep around any
15941                // data that might have already existed
15942                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15943                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15944            }
15945        } catch (PackageManagerException e) {
15946            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15947        }
15948
15949        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15950    }
15951
15952    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15953        try (DigestInputStream digestStream =
15954                new DigestInputStream(new FileInputStream(file), digest)) {
15955            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15956        }
15957    }
15958
15959    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15960            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15961            PackageInstalledInfo res, int installReason) {
15962        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15963
15964        final PackageParser.Package oldPackage;
15965        final PackageSetting ps;
15966        final String pkgName = pkg.packageName;
15967        final int[] allUsers;
15968        final int[] installedUsers;
15969
15970        synchronized(mPackages) {
15971            oldPackage = mPackages.get(pkgName);
15972            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15973
15974            // don't allow upgrade to target a release SDK from a pre-release SDK
15975            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15976                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15977            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15978                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15979            if (oldTargetsPreRelease
15980                    && !newTargetsPreRelease
15981                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15982                Slog.w(TAG, "Can't install package targeting released sdk");
15983                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15984                return;
15985            }
15986
15987            ps = mSettings.mPackages.get(pkgName);
15988
15989            // verify signatures are valid
15990            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
15991            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
15992                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
15993                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15994                            "New package not signed by keys specified by upgrade-keysets: "
15995                                    + pkgName);
15996                    return;
15997                }
15998            } else {
15999
16000                // default to original signature matching
16001                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16002                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16003                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16004                            "New package has a different signature: " + pkgName);
16005                    return;
16006                }
16007            }
16008
16009            // don't allow a system upgrade unless the upgrade hash matches
16010            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16011                byte[] digestBytes = null;
16012                try {
16013                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16014                    updateDigest(digest, new File(pkg.baseCodePath));
16015                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16016                        for (String path : pkg.splitCodePaths) {
16017                            updateDigest(digest, new File(path));
16018                        }
16019                    }
16020                    digestBytes = digest.digest();
16021                } catch (NoSuchAlgorithmException | IOException e) {
16022                    res.setError(INSTALL_FAILED_INVALID_APK,
16023                            "Could not compute hash: " + pkgName);
16024                    return;
16025                }
16026                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16027                    res.setError(INSTALL_FAILED_INVALID_APK,
16028                            "New package fails restrict-update check: " + pkgName);
16029                    return;
16030                }
16031                // retain upgrade restriction
16032                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16033            }
16034
16035            // Check for shared user id changes
16036            String invalidPackageName =
16037                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16038            if (invalidPackageName != null) {
16039                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16040                        "Package " + invalidPackageName + " tried to change user "
16041                                + oldPackage.mSharedUserId);
16042                return;
16043            }
16044
16045            // check if the new package supports all of the abis which the old package supports
16046            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16047            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16048            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16049                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16050                        "Update to package " + pkgName + " doesn't support multi arch");
16051                return;
16052            }
16053
16054            // In case of rollback, remember per-user/profile install state
16055            allUsers = sUserManager.getUserIds();
16056            installedUsers = ps.queryInstalledUsers(allUsers, true);
16057
16058            // don't allow an upgrade from full to ephemeral
16059            if (isInstantApp) {
16060                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16061                    for (int currentUser : allUsers) {
16062                        if (!ps.getInstantApp(currentUser)) {
16063                            // can't downgrade from full to instant
16064                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16065                                    + " for user: " + currentUser);
16066                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16067                            return;
16068                        }
16069                    }
16070                } else if (!ps.getInstantApp(user.getIdentifier())) {
16071                    // can't downgrade from full to instant
16072                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16073                            + " for user: " + user.getIdentifier());
16074                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16075                    return;
16076                }
16077            }
16078        }
16079
16080        // Update what is removed
16081        res.removedInfo = new PackageRemovedInfo(this);
16082        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16083        res.removedInfo.removedPackage = oldPackage.packageName;
16084        res.removedInfo.installerPackageName = ps.installerPackageName;
16085        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16086        res.removedInfo.isUpdate = true;
16087        res.removedInfo.origUsers = installedUsers;
16088        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16089        for (int i = 0; i < installedUsers.length; i++) {
16090            final int userId = installedUsers[i];
16091            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16092        }
16093
16094        final int childCount = (oldPackage.childPackages != null)
16095                ? oldPackage.childPackages.size() : 0;
16096        for (int i = 0; i < childCount; i++) {
16097            boolean childPackageUpdated = false;
16098            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16099            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16100            if (res.addedChildPackages != null) {
16101                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16102                if (childRes != null) {
16103                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16104                    childRes.removedInfo.removedPackage = childPkg.packageName;
16105                    if (childPs != null) {
16106                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16107                    }
16108                    childRes.removedInfo.isUpdate = true;
16109                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16110                    childPackageUpdated = true;
16111                }
16112            }
16113            if (!childPackageUpdated) {
16114                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16115                childRemovedRes.removedPackage = childPkg.packageName;
16116                if (childPs != null) {
16117                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16118                }
16119                childRemovedRes.isUpdate = false;
16120                childRemovedRes.dataRemoved = true;
16121                synchronized (mPackages) {
16122                    if (childPs != null) {
16123                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16124                    }
16125                }
16126                if (res.removedInfo.removedChildPackages == null) {
16127                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16128                }
16129                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16130            }
16131        }
16132
16133        boolean sysPkg = (isSystemApp(oldPackage));
16134        if (sysPkg) {
16135            // Set the system/privileged/oem/vendor/product flags as needed
16136            final boolean privileged =
16137                    (oldPackage.applicationInfo.privateFlags
16138                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16139            final boolean oem =
16140                    (oldPackage.applicationInfo.privateFlags
16141                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16142            final boolean vendor =
16143                    (oldPackage.applicationInfo.privateFlags
16144                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16145            final boolean product =
16146                    (oldPackage.applicationInfo.privateFlags
16147                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16148            final @ParseFlags int systemParseFlags = parseFlags;
16149            final @ScanFlags int systemScanFlags = scanFlags
16150                    | SCAN_AS_SYSTEM
16151                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16152                    | (oem ? SCAN_AS_OEM : 0)
16153                    | (vendor ? SCAN_AS_VENDOR : 0)
16154                    | (product ? SCAN_AS_PRODUCT : 0);
16155
16156            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16157                    user, allUsers, installerPackageName, res, installReason);
16158        } else {
16159            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16160                    user, allUsers, installerPackageName, res, installReason);
16161        }
16162    }
16163
16164    @Override
16165    public List<String> getPreviousCodePaths(String packageName) {
16166        final int callingUid = Binder.getCallingUid();
16167        final List<String> result = new ArrayList<>();
16168        if (getInstantAppPackageName(callingUid) != null) {
16169            return result;
16170        }
16171        final PackageSetting ps = mSettings.mPackages.get(packageName);
16172        if (ps != null
16173                && ps.oldCodePaths != null
16174                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16175            result.addAll(ps.oldCodePaths);
16176        }
16177        return result;
16178    }
16179
16180    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16181            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16182            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16183            String installerPackageName, PackageInstalledInfo res, int installReason) {
16184        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16185                + deletedPackage);
16186
16187        String pkgName = deletedPackage.packageName;
16188        boolean deletedPkg = true;
16189        boolean addedPkg = false;
16190        boolean updatedSettings = false;
16191        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16192        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16193                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16194
16195        final long origUpdateTime = (pkg.mExtras != null)
16196                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16197
16198        // First delete the existing package while retaining the data directory
16199        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16200                res.removedInfo, true, pkg)) {
16201            // If the existing package wasn't successfully deleted
16202            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16203            deletedPkg = false;
16204        } else {
16205            // Successfully deleted the old package; proceed with replace.
16206
16207            // If deleted package lived in a container, give users a chance to
16208            // relinquish resources before killing.
16209            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16210                if (DEBUG_INSTALL) {
16211                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16212                }
16213                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16214                final ArrayList<String> pkgList = new ArrayList<String>(1);
16215                pkgList.add(deletedPackage.applicationInfo.packageName);
16216                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16217            }
16218
16219            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16220                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16221
16222            try {
16223                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16224                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16225                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16226                        installReason);
16227
16228                // Update the in-memory copy of the previous code paths.
16229                PackageSetting ps = mSettings.mPackages.get(pkgName);
16230                if (!killApp) {
16231                    if (ps.oldCodePaths == null) {
16232                        ps.oldCodePaths = new ArraySet<>();
16233                    }
16234                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16235                    if (deletedPackage.splitCodePaths != null) {
16236                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16237                    }
16238                } else {
16239                    ps.oldCodePaths = null;
16240                }
16241                if (ps.childPackageNames != null) {
16242                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16243                        final String childPkgName = ps.childPackageNames.get(i);
16244                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16245                        childPs.oldCodePaths = ps.oldCodePaths;
16246                    }
16247                }
16248                // set instant app status, but, only if it's explicitly specified
16249                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16250                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16251                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16252                prepareAppDataAfterInstallLIF(newPackage);
16253                addedPkg = true;
16254                mDexManager.notifyPackageUpdated(newPackage.packageName,
16255                        newPackage.baseCodePath, newPackage.splitCodePaths);
16256            } catch (PackageManagerException e) {
16257                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16258            }
16259        }
16260
16261        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16262            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16263
16264            // Revert all internal state mutations and added folders for the failed install
16265            if (addedPkg) {
16266                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16267                        res.removedInfo, true, null);
16268            }
16269
16270            // Restore the old package
16271            if (deletedPkg) {
16272                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16273                File restoreFile = new File(deletedPackage.codePath);
16274                // Parse old package
16275                boolean oldExternal = isExternal(deletedPackage);
16276                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16277                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16278                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16279                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16280                try {
16281                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16282                            null);
16283                } catch (PackageManagerException e) {
16284                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16285                            + e.getMessage());
16286                    return;
16287                }
16288
16289                synchronized (mPackages) {
16290                    // Ensure the installer package name up to date
16291                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16292
16293                    // Update permissions for restored package
16294                    mPermissionManager.updatePermissions(
16295                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16296                            mPermissionCallback);
16297
16298                    mSettings.writeLPr();
16299                }
16300
16301                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16302            }
16303        } else {
16304            synchronized (mPackages) {
16305                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16306                if (ps != null) {
16307                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16308                    if (res.removedInfo.removedChildPackages != null) {
16309                        final int childCount = res.removedInfo.removedChildPackages.size();
16310                        // Iterate in reverse as we may modify the collection
16311                        for (int i = childCount - 1; i >= 0; i--) {
16312                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16313                            if (res.addedChildPackages.containsKey(childPackageName)) {
16314                                res.removedInfo.removedChildPackages.removeAt(i);
16315                            } else {
16316                                PackageRemovedInfo childInfo = res.removedInfo
16317                                        .removedChildPackages.valueAt(i);
16318                                childInfo.removedForAllUsers = mPackages.get(
16319                                        childInfo.removedPackage) == null;
16320                            }
16321                        }
16322                    }
16323                }
16324            }
16325        }
16326    }
16327
16328    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16329            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16330            final @ScanFlags int scanFlags, UserHandle user,
16331            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16332            int installReason) {
16333        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16334                + ", old=" + deletedPackage);
16335
16336        final boolean disabledSystem;
16337
16338        // Remove existing system package
16339        removePackageLI(deletedPackage, true);
16340
16341        synchronized (mPackages) {
16342            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16343        }
16344        if (!disabledSystem) {
16345            // We didn't need to disable the .apk as a current system package,
16346            // which means we are replacing another update that is already
16347            // installed.  We need to make sure to delete the older one's .apk.
16348            res.removedInfo.args = createInstallArgsForExisting(0,
16349                    deletedPackage.applicationInfo.getCodePath(),
16350                    deletedPackage.applicationInfo.getResourcePath(),
16351                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16352        } else {
16353            res.removedInfo.args = null;
16354        }
16355
16356        // Successfully disabled the old package. Now proceed with re-installation
16357        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16358                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16359
16360        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16361        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16362                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16363
16364        PackageParser.Package newPackage = null;
16365        try {
16366            // Add the package to the internal data structures
16367            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16368
16369            // Set the update and install times
16370            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16371            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16372                    System.currentTimeMillis());
16373
16374            // Update the package dynamic state if succeeded
16375            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16376                // Now that the install succeeded make sure we remove data
16377                // directories for any child package the update removed.
16378                final int deletedChildCount = (deletedPackage.childPackages != null)
16379                        ? deletedPackage.childPackages.size() : 0;
16380                final int newChildCount = (newPackage.childPackages != null)
16381                        ? newPackage.childPackages.size() : 0;
16382                for (int i = 0; i < deletedChildCount; i++) {
16383                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16384                    boolean childPackageDeleted = true;
16385                    for (int j = 0; j < newChildCount; j++) {
16386                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16387                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16388                            childPackageDeleted = false;
16389                            break;
16390                        }
16391                    }
16392                    if (childPackageDeleted) {
16393                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16394                                deletedChildPkg.packageName);
16395                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16396                            PackageRemovedInfo removedChildRes = res.removedInfo
16397                                    .removedChildPackages.get(deletedChildPkg.packageName);
16398                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16399                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16400                        }
16401                    }
16402                }
16403
16404                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16405                        installReason);
16406                prepareAppDataAfterInstallLIF(newPackage);
16407
16408                mDexManager.notifyPackageUpdated(newPackage.packageName,
16409                            newPackage.baseCodePath, newPackage.splitCodePaths);
16410            }
16411        } catch (PackageManagerException e) {
16412            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16413            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16414        }
16415
16416        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16417            // Re installation failed. Restore old information
16418            // Remove new pkg information
16419            if (newPackage != null) {
16420                removeInstalledPackageLI(newPackage, true);
16421            }
16422            // Add back the old system package
16423            try {
16424                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16425            } catch (PackageManagerException e) {
16426                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16427            }
16428
16429            synchronized (mPackages) {
16430                if (disabledSystem) {
16431                    enableSystemPackageLPw(deletedPackage);
16432                }
16433
16434                // Ensure the installer package name up to date
16435                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16436
16437                // Update permissions for restored package
16438                mPermissionManager.updatePermissions(
16439                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16440                        mPermissionCallback);
16441
16442                mSettings.writeLPr();
16443            }
16444
16445            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16446                    + " after failed upgrade");
16447        }
16448    }
16449
16450    /**
16451     * Checks whether the parent or any of the child packages have a change shared
16452     * user. For a package to be a valid update the shred users of the parent and
16453     * the children should match. We may later support changing child shared users.
16454     * @param oldPkg The updated package.
16455     * @param newPkg The update package.
16456     * @return The shared user that change between the versions.
16457     */
16458    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16459            PackageParser.Package newPkg) {
16460        // Check parent shared user
16461        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16462            return newPkg.packageName;
16463        }
16464        // Check child shared users
16465        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16466        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16467        for (int i = 0; i < newChildCount; i++) {
16468            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16469            // If this child was present, did it have the same shared user?
16470            for (int j = 0; j < oldChildCount; j++) {
16471                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16472                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16473                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16474                    return newChildPkg.packageName;
16475                }
16476            }
16477        }
16478        return null;
16479    }
16480
16481    private void removeNativeBinariesLI(PackageSetting ps) {
16482        // Remove the lib path for the parent package
16483        if (ps != null) {
16484            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16485            // Remove the lib path for the child packages
16486            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16487            for (int i = 0; i < childCount; i++) {
16488                PackageSetting childPs = null;
16489                synchronized (mPackages) {
16490                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16491                }
16492                if (childPs != null) {
16493                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16494                            .legacyNativeLibraryPathString);
16495                }
16496            }
16497        }
16498    }
16499
16500    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16501        // Enable the parent package
16502        mSettings.enableSystemPackageLPw(pkg.packageName);
16503        // Enable the child packages
16504        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16505        for (int i = 0; i < childCount; i++) {
16506            PackageParser.Package childPkg = pkg.childPackages.get(i);
16507            mSettings.enableSystemPackageLPw(childPkg.packageName);
16508        }
16509    }
16510
16511    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16512            PackageParser.Package newPkg) {
16513        // Disable the parent package (parent always replaced)
16514        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16515        // Disable the child packages
16516        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16517        for (int i = 0; i < childCount; i++) {
16518            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16519            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16520            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16521        }
16522        return disabled;
16523    }
16524
16525    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16526            String installerPackageName) {
16527        // Enable the parent package
16528        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16529        // Enable the child packages
16530        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16531        for (int i = 0; i < childCount; i++) {
16532            PackageParser.Package childPkg = pkg.childPackages.get(i);
16533            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16534        }
16535    }
16536
16537    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16538            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16539        // Update the parent package setting
16540        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16541                res, user, installReason);
16542        // Update the child packages setting
16543        final int childCount = (newPackage.childPackages != null)
16544                ? newPackage.childPackages.size() : 0;
16545        for (int i = 0; i < childCount; i++) {
16546            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16547            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16548            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16549                    childRes.origUsers, childRes, user, installReason);
16550        }
16551    }
16552
16553    private void updateSettingsInternalLI(PackageParser.Package pkg,
16554            String installerPackageName, int[] allUsers, int[] installedForUsers,
16555            PackageInstalledInfo res, UserHandle user, int installReason) {
16556        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16557
16558        String pkgName = pkg.packageName;
16559        synchronized (mPackages) {
16560            //write settings. the installStatus will be incomplete at this stage.
16561            //note that the new package setting would have already been
16562            //added to mPackages. It hasn't been persisted yet.
16563            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16564            // TODO: Remove this write? It's also written at the end of this method
16565            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16566            mSettings.writeLPr();
16567            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16568        }
16569
16570        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16571        synchronized (mPackages) {
16572// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16573            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16574                    mPermissionCallback);
16575            // For system-bundled packages, we assume that installing an upgraded version
16576            // of the package implies that the user actually wants to run that new code,
16577            // so we enable the package.
16578            PackageSetting ps = mSettings.mPackages.get(pkgName);
16579            final int userId = user.getIdentifier();
16580            if (ps != null) {
16581                if (isSystemApp(pkg)) {
16582                    if (DEBUG_INSTALL) {
16583                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16584                    }
16585                    // Enable system package for requested users
16586                    if (res.origUsers != null) {
16587                        for (int origUserId : res.origUsers) {
16588                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16589                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16590                                        origUserId, installerPackageName);
16591                            }
16592                        }
16593                    }
16594                    // Also convey the prior install/uninstall state
16595                    if (allUsers != null && installedForUsers != null) {
16596                        for (int currentUserId : allUsers) {
16597                            final boolean installed = ArrayUtils.contains(
16598                                    installedForUsers, currentUserId);
16599                            if (DEBUG_INSTALL) {
16600                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16601                            }
16602                            ps.setInstalled(installed, currentUserId);
16603                        }
16604                        // these install state changes will be persisted in the
16605                        // upcoming call to mSettings.writeLPr().
16606                    }
16607                }
16608                // It's implied that when a user requests installation, they want the app to be
16609                // installed and enabled.
16610                if (userId != UserHandle.USER_ALL) {
16611                    ps.setInstalled(true, userId);
16612                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16613                }
16614
16615                // When replacing an existing package, preserve the original install reason for all
16616                // users that had the package installed before.
16617                final Set<Integer> previousUserIds = new ArraySet<>();
16618                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16619                    final int installReasonCount = res.removedInfo.installReasons.size();
16620                    for (int i = 0; i < installReasonCount; i++) {
16621                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16622                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16623                        ps.setInstallReason(previousInstallReason, previousUserId);
16624                        previousUserIds.add(previousUserId);
16625                    }
16626                }
16627
16628                // Set install reason for users that are having the package newly installed.
16629                if (userId == UserHandle.USER_ALL) {
16630                    for (int currentUserId : sUserManager.getUserIds()) {
16631                        if (!previousUserIds.contains(currentUserId)) {
16632                            ps.setInstallReason(installReason, currentUserId);
16633                        }
16634                    }
16635                } else if (!previousUserIds.contains(userId)) {
16636                    ps.setInstallReason(installReason, userId);
16637                }
16638                mSettings.writeKernelMappingLPr(ps);
16639            }
16640            res.name = pkgName;
16641            res.uid = pkg.applicationInfo.uid;
16642            res.pkg = pkg;
16643            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16644            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16645            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16646            //to update install status
16647            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16648            mSettings.writeLPr();
16649            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16650        }
16651
16652        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16653    }
16654
16655    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16656        try {
16657            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16658            installPackageLI(args, res);
16659        } finally {
16660            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16661        }
16662    }
16663
16664    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16665        final int installFlags = args.installFlags;
16666        final String installerPackageName = args.installerPackageName;
16667        final String volumeUuid = args.volumeUuid;
16668        final File tmpPackageFile = new File(args.getCodePath());
16669        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16670        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16671                || (args.volumeUuid != null));
16672        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16673        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16674        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16675        final boolean virtualPreload =
16676                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16677        boolean replace = false;
16678        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16679        if (args.move != null) {
16680            // moving a complete application; perform an initial scan on the new install location
16681            scanFlags |= SCAN_INITIAL;
16682        }
16683        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16684            scanFlags |= SCAN_DONT_KILL_APP;
16685        }
16686        if (instantApp) {
16687            scanFlags |= SCAN_AS_INSTANT_APP;
16688        }
16689        if (fullApp) {
16690            scanFlags |= SCAN_AS_FULL_APP;
16691        }
16692        if (virtualPreload) {
16693            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16694        }
16695
16696        // Result object to be returned
16697        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16698        res.installerPackageName = installerPackageName;
16699
16700        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16701
16702        // Sanity check
16703        if (instantApp && (forwardLocked || onExternal)) {
16704            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16705                    + " external=" + onExternal);
16706            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16707            return;
16708        }
16709
16710        // Retrieve PackageSettings and parse package
16711        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16712                | PackageParser.PARSE_ENFORCE_CODE
16713                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16714                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16715                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16716        PackageParser pp = new PackageParser();
16717        pp.setSeparateProcesses(mSeparateProcesses);
16718        pp.setDisplayMetrics(mMetrics);
16719        pp.setCallback(mPackageParserCallback);
16720
16721        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16722        final PackageParser.Package pkg;
16723        try {
16724            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16725            DexMetadataHelper.validatePackageDexMetadata(pkg);
16726        } catch (PackageParserException e) {
16727            res.setError("Failed parse during installPackageLI", e);
16728            return;
16729        } finally {
16730            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16731        }
16732
16733        // Instant apps have several additional install-time checks.
16734        if (instantApp) {
16735            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16736                Slog.w(TAG,
16737                        "Instant app package " + pkg.packageName + " does not target at least O");
16738                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16739                        "Instant app package must target at least O");
16740                return;
16741            }
16742            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16743                Slog.w(TAG, "Instant app package " + pkg.packageName
16744                        + " does not target targetSandboxVersion 2");
16745                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16746                        "Instant app package must use targetSandboxVersion 2");
16747                return;
16748            }
16749            if (pkg.mSharedUserId != null) {
16750                Slog.w(TAG, "Instant app package " + pkg.packageName
16751                        + " may not declare sharedUserId.");
16752                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16753                        "Instant app package may not declare a sharedUserId");
16754                return;
16755            }
16756        }
16757
16758        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16759            // Static shared libraries have synthetic package names
16760            renameStaticSharedLibraryPackage(pkg);
16761
16762            // No static shared libs on external storage
16763            if (onExternal) {
16764                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16765                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16766                        "Packages declaring static-shared libs cannot be updated");
16767                return;
16768            }
16769        }
16770
16771        // If we are installing a clustered package add results for the children
16772        if (pkg.childPackages != null) {
16773            synchronized (mPackages) {
16774                final int childCount = pkg.childPackages.size();
16775                for (int i = 0; i < childCount; i++) {
16776                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16777                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16778                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16779                    childRes.pkg = childPkg;
16780                    childRes.name = childPkg.packageName;
16781                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16782                    if (childPs != null) {
16783                        childRes.origUsers = childPs.queryInstalledUsers(
16784                                sUserManager.getUserIds(), true);
16785                    }
16786                    if ((mPackages.containsKey(childPkg.packageName))) {
16787                        childRes.removedInfo = new PackageRemovedInfo(this);
16788                        childRes.removedInfo.removedPackage = childPkg.packageName;
16789                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16790                    }
16791                    if (res.addedChildPackages == null) {
16792                        res.addedChildPackages = new ArrayMap<>();
16793                    }
16794                    res.addedChildPackages.put(childPkg.packageName, childRes);
16795                }
16796            }
16797        }
16798
16799        // If package doesn't declare API override, mark that we have an install
16800        // time CPU ABI override.
16801        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16802            pkg.cpuAbiOverride = args.abiOverride;
16803        }
16804
16805        String pkgName = res.name = pkg.packageName;
16806        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16807            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16808                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16809                return;
16810            }
16811        }
16812
16813        try {
16814            // either use what we've been given or parse directly from the APK
16815            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16816                pkg.setSigningDetails(args.signingDetails);
16817            } else {
16818                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16819            }
16820        } catch (PackageParserException e) {
16821            res.setError("Failed collect during installPackageLI", e);
16822            return;
16823        }
16824
16825        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16826                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16827            Slog.w(TAG, "Instant app package " + pkg.packageName
16828                    + " is not signed with at least APK Signature Scheme v2");
16829            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16830                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16831            return;
16832        }
16833
16834        // Get rid of all references to package scan path via parser.
16835        pp = null;
16836        String oldCodePath = null;
16837        boolean systemApp = false;
16838        synchronized (mPackages) {
16839            // Check if installing already existing package
16840            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16841                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16842                if (pkg.mOriginalPackages != null
16843                        && pkg.mOriginalPackages.contains(oldName)
16844                        && mPackages.containsKey(oldName)) {
16845                    // This package is derived from an original package,
16846                    // and this device has been updating from that original
16847                    // name.  We must continue using the original name, so
16848                    // rename the new package here.
16849                    pkg.setPackageName(oldName);
16850                    pkgName = pkg.packageName;
16851                    replace = true;
16852                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16853                            + oldName + " pkgName=" + pkgName);
16854                } else if (mPackages.containsKey(pkgName)) {
16855                    // This package, under its official name, already exists
16856                    // on the device; we should replace it.
16857                    replace = true;
16858                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16859                }
16860
16861                // Child packages are installed through the parent package
16862                if (pkg.parentPackage != null) {
16863                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16864                            "Package " + pkg.packageName + " is child of package "
16865                                    + pkg.parentPackage.parentPackage + ". Child packages "
16866                                    + "can be updated only through the parent package.");
16867                    return;
16868                }
16869
16870                if (replace) {
16871                    // Prevent apps opting out from runtime permissions
16872                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16873                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16874                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16875                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16876                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16877                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16878                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16879                                        + " doesn't support runtime permissions but the old"
16880                                        + " target SDK " + oldTargetSdk + " does.");
16881                        return;
16882                    }
16883                    // Prevent persistent apps from being updated
16884                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16885                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16886                                "Package " + oldPackage.packageName + " is a persistent app. "
16887                                        + "Persistent apps are not updateable.");
16888                        return;
16889                    }
16890                    // Prevent apps from downgrading their targetSandbox.
16891                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16892                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16893                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16894                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16895                                "Package " + pkg.packageName + " new target sandbox "
16896                                + newTargetSandbox + " is incompatible with the previous value of"
16897                                + oldTargetSandbox + ".");
16898                        return;
16899                    }
16900
16901                    // Prevent installing of child packages
16902                    if (oldPackage.parentPackage != null) {
16903                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16904                                "Package " + pkg.packageName + " is child of package "
16905                                        + oldPackage.parentPackage + ". Child packages "
16906                                        + "can be updated only through the parent package.");
16907                        return;
16908                    }
16909                }
16910            }
16911
16912            PackageSetting ps = mSettings.mPackages.get(pkgName);
16913            if (ps != null) {
16914                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16915
16916                // Static shared libs have same package with different versions where
16917                // we internally use a synthetic package name to allow multiple versions
16918                // of the same package, therefore we need to compare signatures against
16919                // the package setting for the latest library version.
16920                PackageSetting signatureCheckPs = ps;
16921                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16922                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16923                    if (libraryEntry != null) {
16924                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16925                    }
16926                }
16927
16928                // Quick sanity check that we're signed correctly if updating;
16929                // we'll check this again later when scanning, but we want to
16930                // bail early here before tripping over redefined permissions.
16931                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16932                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16933                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16934                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16935                                + pkg.packageName + " upgrade keys do not match the "
16936                                + "previously installed version");
16937                        return;
16938                    }
16939                } else {
16940                    try {
16941                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16942                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16943                        // We don't care about disabledPkgSetting on install for now.
16944                        final boolean compatMatch = verifySignatures(
16945                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
16946                                compareRecover);
16947                        // The new KeySets will be re-added later in the scanning process.
16948                        if (compatMatch) {
16949                            synchronized (mPackages) {
16950                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16951                            }
16952                        }
16953                    } catch (PackageManagerException e) {
16954                        res.setError(e.error, e.getMessage());
16955                        return;
16956                    }
16957                }
16958
16959                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16960                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16961                    systemApp = (ps.pkg.applicationInfo.flags &
16962                            ApplicationInfo.FLAG_SYSTEM) != 0;
16963                }
16964                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16965            }
16966
16967            int N = pkg.permissions.size();
16968            for (int i = N-1; i >= 0; i--) {
16969                final PackageParser.Permission perm = pkg.permissions.get(i);
16970                final BasePermission bp =
16971                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16972
16973                // Don't allow anyone but the system to define ephemeral permissions.
16974                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16975                        && !systemApp) {
16976                    Slog.w(TAG, "Non-System package " + pkg.packageName
16977                            + " attempting to delcare ephemeral permission "
16978                            + perm.info.name + "; Removing ephemeral.");
16979                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16980                }
16981
16982                // Check whether the newly-scanned package wants to define an already-defined perm
16983                if (bp != null) {
16984                    // If the defining package is signed with our cert, it's okay.  This
16985                    // also includes the "updating the same package" case, of course.
16986                    // "updating same package" could also involve key-rotation.
16987                    final boolean sigsOk;
16988                    final String sourcePackageName = bp.getSourcePackageName();
16989                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
16990                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16991                    if (sourcePackageName.equals(pkg.packageName)
16992                            && (ksms.shouldCheckUpgradeKeySetLocked(
16993                                    sourcePackageSetting, scanFlags))) {
16994                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
16995                    } else {
16996
16997                        // in the event of signing certificate rotation, we need to see if the
16998                        // package's certificate has rotated from the current one, or if it is an
16999                        // older certificate with which the current is ok with sharing permissions
17000                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17001                                        pkg.mSigningDetails,
17002                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17003                            sigsOk = true;
17004                        } else if (pkg.mSigningDetails.checkCapability(
17005                                        sourcePackageSetting.signatures.mSigningDetails,
17006                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17007
17008                            // the scanned package checks out, has signing certificate rotation
17009                            // history, and is newer; bring it over
17010                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17011                            sigsOk = true;
17012                        } else {
17013                            sigsOk = false;
17014                        }
17015                    }
17016                    if (!sigsOk) {
17017                        // If the owning package is the system itself, we log but allow
17018                        // install to proceed; we fail the install on all other permission
17019                        // redefinitions.
17020                        if (!sourcePackageName.equals("android")) {
17021                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17022                                    + pkg.packageName + " attempting to redeclare permission "
17023                                    + perm.info.name + " already owned by " + sourcePackageName);
17024                            res.origPermission = perm.info.name;
17025                            res.origPackage = sourcePackageName;
17026                            return;
17027                        } else {
17028                            Slog.w(TAG, "Package " + pkg.packageName
17029                                    + " attempting to redeclare system permission "
17030                                    + perm.info.name + "; ignoring new declaration");
17031                            pkg.permissions.remove(i);
17032                        }
17033                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17034                        // Prevent apps to change protection level to dangerous from any other
17035                        // type as this would allow a privilege escalation where an app adds a
17036                        // normal/signature permission in other app's group and later redefines
17037                        // it as dangerous leading to the group auto-grant.
17038                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17039                                == PermissionInfo.PROTECTION_DANGEROUS) {
17040                            if (bp != null && !bp.isRuntime()) {
17041                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17042                                        + "non-runtime permission " + perm.info.name
17043                                        + " to runtime; keeping old protection level");
17044                                perm.info.protectionLevel = bp.getProtectionLevel();
17045                            }
17046                        }
17047                    }
17048                }
17049            }
17050        }
17051
17052        if (systemApp) {
17053            if (onExternal) {
17054                // Abort update; system app can't be replaced with app on sdcard
17055                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17056                        "Cannot install updates to system apps on sdcard");
17057                return;
17058            } else if (instantApp) {
17059                // Abort update; system app can't be replaced with an instant app
17060                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17061                        "Cannot update a system app with an instant app");
17062                return;
17063            }
17064        }
17065
17066        if (args.move != null) {
17067            // We did an in-place move, so dex is ready to roll
17068            scanFlags |= SCAN_NO_DEX;
17069            scanFlags |= SCAN_MOVE;
17070
17071            synchronized (mPackages) {
17072                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17073                if (ps == null) {
17074                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17075                            "Missing settings for moved package " + pkgName);
17076                }
17077
17078                // We moved the entire application as-is, so bring over the
17079                // previously derived ABI information.
17080                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17081                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17082            }
17083
17084        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17085            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17086            scanFlags |= SCAN_NO_DEX;
17087
17088            try {
17089                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17090                    args.abiOverride : pkg.cpuAbiOverride);
17091                final boolean extractNativeLibs = !pkg.isLibrary();
17092                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17093            } catch (PackageManagerException pme) {
17094                Slog.e(TAG, "Error deriving application ABI", pme);
17095                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17096                return;
17097            }
17098
17099            // Shared libraries for the package need to be updated.
17100            synchronized (mPackages) {
17101                try {
17102                    updateSharedLibrariesLPr(pkg, null);
17103                } catch (PackageManagerException e) {
17104                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17105                }
17106            }
17107        }
17108
17109        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17110            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17111            return;
17112        }
17113
17114        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17115            String apkPath = null;
17116            synchronized (mPackages) {
17117                // Note that if the attacker managed to skip verify setup, for example by tampering
17118                // with the package settings, upon reboot we will do full apk verification when
17119                // verity is not detected.
17120                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17121                if (ps != null && ps.isPrivileged()) {
17122                    apkPath = pkg.baseCodePath;
17123                }
17124            }
17125
17126            if (apkPath != null) {
17127                final VerityUtils.SetupResult result =
17128                        VerityUtils.generateApkVeritySetupData(apkPath);
17129                if (result.isOk()) {
17130                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17131                    FileDescriptor fd = result.getUnownedFileDescriptor();
17132                    try {
17133                        mInstaller.installApkVerity(apkPath, fd);
17134                    } catch (InstallerException e) {
17135                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17136                                "Failed to set up verity: " + e);
17137                        return;
17138                    } finally {
17139                        IoUtils.closeQuietly(fd);
17140                    }
17141                } else if (result.isFailed()) {
17142                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17143                    return;
17144                } else {
17145                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17146                    // reboot.
17147                }
17148            }
17149        }
17150
17151        if (!instantApp) {
17152            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17153        } else {
17154            if (DEBUG_DOMAIN_VERIFICATION) {
17155                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17156            }
17157        }
17158
17159        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17160                "installPackageLI")) {
17161            if (replace) {
17162                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17163                    // Static libs have a synthetic package name containing the version
17164                    // and cannot be updated as an update would get a new package name,
17165                    // unless this is the exact same version code which is useful for
17166                    // development.
17167                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17168                    if (existingPkg != null &&
17169                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17170                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17171                                + "static-shared libs cannot be updated");
17172                        return;
17173                    }
17174                }
17175                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17176                        installerPackageName, res, args.installReason);
17177            } else {
17178                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17179                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17180            }
17181        }
17182
17183        // Prepare the application profiles for the new code paths.
17184        // This needs to be done before invoking dexopt so that any install-time profile
17185        // can be used for optimizations.
17186        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17187
17188        // Check whether we need to dexopt the app.
17189        //
17190        // NOTE: it is IMPORTANT to call dexopt:
17191        //   - after doRename which will sync the package data from PackageParser.Package and its
17192        //     corresponding ApplicationInfo.
17193        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17194        //     uid of the application (pkg.applicationInfo.uid).
17195        //     This update happens in place!
17196        //
17197        // We only need to dexopt if the package meets ALL of the following conditions:
17198        //   1) it is not forward locked.
17199        //   2) it is not on on an external ASEC container.
17200        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17201        //
17202        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17203        // complete, so we skip this step during installation. Instead, we'll take extra time
17204        // the first time the instant app starts. It's preferred to do it this way to provide
17205        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17206        // middle of running an instant app. The default behaviour can be overridden
17207        // via gservices.
17208        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17209                && !forwardLocked
17210                && !pkg.applicationInfo.isExternalAsec()
17211                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17212                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17213
17214        if (performDexopt) {
17215            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17216            // Do not run PackageDexOptimizer through the local performDexOpt
17217            // method because `pkg` may not be in `mPackages` yet.
17218            //
17219            // Also, don't fail application installs if the dexopt step fails.
17220            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17221                    REASON_INSTALL,
17222                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17223                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17224            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17225                    null /* instructionSets */,
17226                    getOrCreateCompilerPackageStats(pkg),
17227                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17228                    dexoptOptions);
17229            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17230        }
17231
17232        // Notify BackgroundDexOptService that the package has been changed.
17233        // If this is an update of a package which used to fail to compile,
17234        // BackgroundDexOptService will remove it from its blacklist.
17235        // TODO: Layering violation
17236        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17237
17238        synchronized (mPackages) {
17239            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17240            if (ps != null) {
17241                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17242                ps.setUpdateAvailable(false /*updateAvailable*/);
17243            }
17244
17245            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17246            for (int i = 0; i < childCount; i++) {
17247                PackageParser.Package childPkg = pkg.childPackages.get(i);
17248                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17249                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17250                if (childPs != null) {
17251                    childRes.newUsers = childPs.queryInstalledUsers(
17252                            sUserManager.getUserIds(), true);
17253                }
17254            }
17255
17256            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17257                updateSequenceNumberLP(ps, res.newUsers);
17258                updateInstantAppInstallerLocked(pkgName);
17259            }
17260        }
17261    }
17262
17263    private void startIntentFilterVerifications(int userId, boolean replacing,
17264            PackageParser.Package pkg) {
17265        if (mIntentFilterVerifierComponent == null) {
17266            Slog.w(TAG, "No IntentFilter verification will not be done as "
17267                    + "there is no IntentFilterVerifier available!");
17268            return;
17269        }
17270
17271        final int verifierUid = getPackageUid(
17272                mIntentFilterVerifierComponent.getPackageName(),
17273                MATCH_DEBUG_TRIAGED_MISSING,
17274                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17275
17276        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17277        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17278        mHandler.sendMessage(msg);
17279
17280        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17281        for (int i = 0; i < childCount; i++) {
17282            PackageParser.Package childPkg = pkg.childPackages.get(i);
17283            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17284            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17285            mHandler.sendMessage(msg);
17286        }
17287    }
17288
17289    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17290            PackageParser.Package pkg) {
17291        int size = pkg.activities.size();
17292        if (size == 0) {
17293            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17294                    "No activity, so no need to verify any IntentFilter!");
17295            return;
17296        }
17297
17298        final boolean hasDomainURLs = hasDomainURLs(pkg);
17299        if (!hasDomainURLs) {
17300            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17301                    "No domain URLs, so no need to verify any IntentFilter!");
17302            return;
17303        }
17304
17305        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17306                + " if any IntentFilter from the " + size
17307                + " Activities needs verification ...");
17308
17309        int count = 0;
17310        final String packageName = pkg.packageName;
17311
17312        synchronized (mPackages) {
17313            // If this is a new install and we see that we've already run verification for this
17314            // package, we have nothing to do: it means the state was restored from backup.
17315            if (!replacing) {
17316                IntentFilterVerificationInfo ivi =
17317                        mSettings.getIntentFilterVerificationLPr(packageName);
17318                if (ivi != null) {
17319                    if (DEBUG_DOMAIN_VERIFICATION) {
17320                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17321                                + ivi.getStatusString());
17322                    }
17323                    return;
17324                }
17325            }
17326
17327            // If any filters need to be verified, then all need to be.
17328            boolean needToVerify = false;
17329            for (PackageParser.Activity a : pkg.activities) {
17330                for (ActivityIntentInfo filter : a.intents) {
17331                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17332                        if (DEBUG_DOMAIN_VERIFICATION) {
17333                            Slog.d(TAG,
17334                                    "Intent filter needs verification, so processing all filters");
17335                        }
17336                        needToVerify = true;
17337                        break;
17338                    }
17339                }
17340            }
17341
17342            if (needToVerify) {
17343                final int verificationId = mIntentFilterVerificationToken++;
17344                for (PackageParser.Activity a : pkg.activities) {
17345                    for (ActivityIntentInfo filter : a.intents) {
17346                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17347                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17348                                    "Verification needed for IntentFilter:" + filter.toString());
17349                            mIntentFilterVerifier.addOneIntentFilterVerification(
17350                                    verifierUid, userId, verificationId, filter, packageName);
17351                            count++;
17352                        }
17353                    }
17354                }
17355            }
17356        }
17357
17358        if (count > 0) {
17359            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17360                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17361                    +  " for userId:" + userId);
17362            mIntentFilterVerifier.startVerifications(userId);
17363        } else {
17364            if (DEBUG_DOMAIN_VERIFICATION) {
17365                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17366            }
17367        }
17368    }
17369
17370    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17371        final ComponentName cn  = filter.activity.getComponentName();
17372        final String packageName = cn.getPackageName();
17373
17374        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17375                packageName);
17376        if (ivi == null) {
17377            return true;
17378        }
17379        int status = ivi.getStatus();
17380        switch (status) {
17381            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17382            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17383                return true;
17384
17385            default:
17386                // Nothing to do
17387                return false;
17388        }
17389    }
17390
17391    private static boolean isMultiArch(ApplicationInfo info) {
17392        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17393    }
17394
17395    private static boolean isExternal(PackageParser.Package pkg) {
17396        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17397    }
17398
17399    private static boolean isExternal(PackageSetting ps) {
17400        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17401    }
17402
17403    private static boolean isSystemApp(PackageParser.Package pkg) {
17404        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17405    }
17406
17407    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17408        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17409    }
17410
17411    private static boolean isOemApp(PackageParser.Package pkg) {
17412        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17413    }
17414
17415    private static boolean isVendorApp(PackageParser.Package pkg) {
17416        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17417    }
17418
17419    private static boolean isProductApp(PackageParser.Package pkg) {
17420        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17421    }
17422
17423    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17424        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17425    }
17426
17427    private static boolean isSystemApp(PackageSetting ps) {
17428        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17429    }
17430
17431    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17432        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17433    }
17434
17435    private int packageFlagsToInstallFlags(PackageSetting ps) {
17436        int installFlags = 0;
17437        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17438            // This existing package was an external ASEC install when we have
17439            // the external flag without a UUID
17440            installFlags |= PackageManager.INSTALL_EXTERNAL;
17441        }
17442        if (ps.isForwardLocked()) {
17443            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17444        }
17445        return installFlags;
17446    }
17447
17448    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17449        if (isExternal(pkg)) {
17450            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17451                return mSettings.getExternalVersion();
17452            } else {
17453                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17454            }
17455        } else {
17456            return mSettings.getInternalVersion();
17457        }
17458    }
17459
17460    private void deleteTempPackageFiles() {
17461        final FilenameFilter filter = new FilenameFilter() {
17462            public boolean accept(File dir, String name) {
17463                return name.startsWith("vmdl") && name.endsWith(".tmp");
17464            }
17465        };
17466        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17467            file.delete();
17468        }
17469    }
17470
17471    @Override
17472    public void deletePackageAsUser(String packageName, int versionCode,
17473            IPackageDeleteObserver observer, int userId, int flags) {
17474        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17475                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17476    }
17477
17478    @Override
17479    public void deletePackageVersioned(VersionedPackage versionedPackage,
17480            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17481        final int callingUid = Binder.getCallingUid();
17482        mContext.enforceCallingOrSelfPermission(
17483                android.Manifest.permission.DELETE_PACKAGES, null);
17484        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17485        Preconditions.checkNotNull(versionedPackage);
17486        Preconditions.checkNotNull(observer);
17487        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17488                PackageManager.VERSION_CODE_HIGHEST,
17489                Long.MAX_VALUE, "versionCode must be >= -1");
17490
17491        final String packageName = versionedPackage.getPackageName();
17492        final long versionCode = versionedPackage.getLongVersionCode();
17493        final String internalPackageName;
17494        synchronized (mPackages) {
17495            // Normalize package name to handle renamed packages and static libs
17496            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17497        }
17498
17499        final int uid = Binder.getCallingUid();
17500        if (!isOrphaned(internalPackageName)
17501                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17502            try {
17503                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17504                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17505                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17506                observer.onUserActionRequired(intent);
17507            } catch (RemoteException re) {
17508            }
17509            return;
17510        }
17511        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17512        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17513        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17514            mContext.enforceCallingOrSelfPermission(
17515                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17516                    "deletePackage for user " + userId);
17517        }
17518
17519        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17520            try {
17521                observer.onPackageDeleted(packageName,
17522                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17523            } catch (RemoteException re) {
17524            }
17525            return;
17526        }
17527
17528        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17529            try {
17530                observer.onPackageDeleted(packageName,
17531                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17532            } catch (RemoteException re) {
17533            }
17534            return;
17535        }
17536
17537        if (DEBUG_REMOVE) {
17538            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17539                    + " deleteAllUsers: " + deleteAllUsers + " version="
17540                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17541                    ? "VERSION_CODE_HIGHEST" : versionCode));
17542        }
17543        // Queue up an async operation since the package deletion may take a little while.
17544        mHandler.post(new Runnable() {
17545            public void run() {
17546                mHandler.removeCallbacks(this);
17547                int returnCode;
17548                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17549                boolean doDeletePackage = true;
17550                if (ps != null) {
17551                    final boolean targetIsInstantApp =
17552                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17553                    doDeletePackage = !targetIsInstantApp
17554                            || canViewInstantApps;
17555                }
17556                if (doDeletePackage) {
17557                    if (!deleteAllUsers) {
17558                        returnCode = deletePackageX(internalPackageName, versionCode,
17559                                userId, deleteFlags);
17560                    } else {
17561                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17562                                internalPackageName, users);
17563                        // If nobody is blocking uninstall, proceed with delete for all users
17564                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17565                            returnCode = deletePackageX(internalPackageName, versionCode,
17566                                    userId, deleteFlags);
17567                        } else {
17568                            // Otherwise uninstall individually for users with blockUninstalls=false
17569                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17570                            for (int userId : users) {
17571                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17572                                    returnCode = deletePackageX(internalPackageName, versionCode,
17573                                            userId, userFlags);
17574                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17575                                        Slog.w(TAG, "Package delete failed for user " + userId
17576                                                + ", returnCode " + returnCode);
17577                                    }
17578                                }
17579                            }
17580                            // The app has only been marked uninstalled for certain users.
17581                            // We still need to report that delete was blocked
17582                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17583                        }
17584                    }
17585                } else {
17586                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17587                }
17588                try {
17589                    observer.onPackageDeleted(packageName, returnCode, null);
17590                } catch (RemoteException e) {
17591                    Log.i(TAG, "Observer no longer exists.");
17592                } //end catch
17593            } //end run
17594        });
17595    }
17596
17597    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17598        if (pkg.staticSharedLibName != null) {
17599            return pkg.manifestPackageName;
17600        }
17601        return pkg.packageName;
17602    }
17603
17604    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17605        // Handle renamed packages
17606        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17607        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17608
17609        // Is this a static library?
17610        LongSparseArray<SharedLibraryEntry> versionedLib =
17611                mStaticLibsByDeclaringPackage.get(packageName);
17612        if (versionedLib == null || versionedLib.size() <= 0) {
17613            return packageName;
17614        }
17615
17616        // Figure out which lib versions the caller can see
17617        LongSparseLongArray versionsCallerCanSee = null;
17618        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17619        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17620                && callingAppId != Process.ROOT_UID) {
17621            versionsCallerCanSee = new LongSparseLongArray();
17622            String libName = versionedLib.valueAt(0).info.getName();
17623            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17624            if (uidPackages != null) {
17625                for (String uidPackage : uidPackages) {
17626                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17627                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17628                    if (libIdx >= 0) {
17629                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17630                        versionsCallerCanSee.append(libVersion, libVersion);
17631                    }
17632                }
17633            }
17634        }
17635
17636        // Caller can see nothing - done
17637        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17638            return packageName;
17639        }
17640
17641        // Find the version the caller can see and the app version code
17642        SharedLibraryEntry highestVersion = null;
17643        final int versionCount = versionedLib.size();
17644        for (int i = 0; i < versionCount; i++) {
17645            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17646            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17647                    libEntry.info.getLongVersion()) < 0) {
17648                continue;
17649            }
17650            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17651            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17652                if (libVersionCode == versionCode) {
17653                    return libEntry.apk;
17654                }
17655            } else if (highestVersion == null) {
17656                highestVersion = libEntry;
17657            } else if (libVersionCode  > highestVersion.info
17658                    .getDeclaringPackage().getLongVersionCode()) {
17659                highestVersion = libEntry;
17660            }
17661        }
17662
17663        if (highestVersion != null) {
17664            return highestVersion.apk;
17665        }
17666
17667        return packageName;
17668    }
17669
17670    boolean isCallerVerifier(int callingUid) {
17671        final int callingUserId = UserHandle.getUserId(callingUid);
17672        return mRequiredVerifierPackage != null &&
17673                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17674    }
17675
17676    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17677        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17678              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17679            return true;
17680        }
17681        final int callingUserId = UserHandle.getUserId(callingUid);
17682        // If the caller installed the pkgName, then allow it to silently uninstall.
17683        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17684            return true;
17685        }
17686
17687        // Allow package verifier to silently uninstall.
17688        if (mRequiredVerifierPackage != null &&
17689                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17690            return true;
17691        }
17692
17693        // Allow package uninstaller to silently uninstall.
17694        if (mRequiredUninstallerPackage != null &&
17695                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17696            return true;
17697        }
17698
17699        // Allow storage manager to silently uninstall.
17700        if (mStorageManagerPackage != null &&
17701                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17702            return true;
17703        }
17704
17705        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17706        // uninstall for device owner provisioning.
17707        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17708                == PERMISSION_GRANTED) {
17709            return true;
17710        }
17711
17712        return false;
17713    }
17714
17715    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17716        int[] result = EMPTY_INT_ARRAY;
17717        for (int userId : userIds) {
17718            if (getBlockUninstallForUser(packageName, userId)) {
17719                result = ArrayUtils.appendInt(result, userId);
17720            }
17721        }
17722        return result;
17723    }
17724
17725    @Override
17726    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17727        final int callingUid = Binder.getCallingUid();
17728        if (getInstantAppPackageName(callingUid) != null
17729                && !isCallerSameApp(packageName, callingUid)) {
17730            return false;
17731        }
17732        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17733    }
17734
17735    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17736        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17737                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17738        try {
17739            if (dpm != null) {
17740                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17741                        /* callingUserOnly =*/ false);
17742                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17743                        : deviceOwnerComponentName.getPackageName();
17744                // Does the package contains the device owner?
17745                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17746                // this check is probably not needed, since DO should be registered as a device
17747                // admin on some user too. (Original bug for this: b/17657954)
17748                if (packageName.equals(deviceOwnerPackageName)) {
17749                    return true;
17750                }
17751                // Does it contain a device admin for any user?
17752                int[] users;
17753                if (userId == UserHandle.USER_ALL) {
17754                    users = sUserManager.getUserIds();
17755                } else {
17756                    users = new int[]{userId};
17757                }
17758                for (int i = 0; i < users.length; ++i) {
17759                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17760                        return true;
17761                    }
17762                }
17763            }
17764        } catch (RemoteException e) {
17765        }
17766        return false;
17767    }
17768
17769    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17770        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17771    }
17772
17773    /**
17774     *  This method is an internal method that could be get invoked either
17775     *  to delete an installed package or to clean up a failed installation.
17776     *  After deleting an installed package, a broadcast is sent to notify any
17777     *  listeners that the package has been removed. For cleaning up a failed
17778     *  installation, the broadcast is not necessary since the package's
17779     *  installation wouldn't have sent the initial broadcast either
17780     *  The key steps in deleting a package are
17781     *  deleting the package information in internal structures like mPackages,
17782     *  deleting the packages base directories through installd
17783     *  updating mSettings to reflect current status
17784     *  persisting settings for later use
17785     *  sending a broadcast if necessary
17786     */
17787    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17788        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17789        final boolean res;
17790
17791        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17792                ? UserHandle.USER_ALL : userId;
17793
17794        if (isPackageDeviceAdmin(packageName, removeUser)) {
17795            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17796            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17797        }
17798
17799        PackageSetting uninstalledPs = null;
17800        PackageParser.Package pkg = null;
17801
17802        // for the uninstall-updates case and restricted profiles, remember the per-
17803        // user handle installed state
17804        int[] allUsers;
17805        synchronized (mPackages) {
17806            uninstalledPs = mSettings.mPackages.get(packageName);
17807            if (uninstalledPs == null) {
17808                Slog.w(TAG, "Not removing non-existent package " + packageName);
17809                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17810            }
17811
17812            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17813                    && uninstalledPs.versionCode != versionCode) {
17814                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17815                        + uninstalledPs.versionCode + " != " + versionCode);
17816                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17817            }
17818
17819            // Static shared libs can be declared by any package, so let us not
17820            // allow removing a package if it provides a lib others depend on.
17821            pkg = mPackages.get(packageName);
17822
17823            allUsers = sUserManager.getUserIds();
17824
17825            if (pkg != null && pkg.staticSharedLibName != null) {
17826                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17827                        pkg.staticSharedLibVersion);
17828                if (libEntry != null) {
17829                    for (int currUserId : allUsers) {
17830                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17831                            continue;
17832                        }
17833                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17834                                libEntry.info, 0, currUserId);
17835                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17836                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17837                                    + " hosting lib " + libEntry.info.getName() + " version "
17838                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17839                                    + " for user " + currUserId);
17840                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17841                        }
17842                    }
17843                }
17844            }
17845
17846            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17847        }
17848
17849        final int freezeUser;
17850        if (isUpdatedSystemApp(uninstalledPs)
17851                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17852            // We're downgrading a system app, which will apply to all users, so
17853            // freeze them all during the downgrade
17854            freezeUser = UserHandle.USER_ALL;
17855        } else {
17856            freezeUser = removeUser;
17857        }
17858
17859        synchronized (mInstallLock) {
17860            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17861            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17862                    deleteFlags, "deletePackageX")) {
17863                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17864                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17865            }
17866            synchronized (mPackages) {
17867                if (res) {
17868                    if (pkg != null) {
17869                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17870                    }
17871                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17872                    updateInstantAppInstallerLocked(packageName);
17873                }
17874            }
17875        }
17876
17877        if (res) {
17878            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17879            info.sendPackageRemovedBroadcasts(killApp);
17880            info.sendSystemPackageUpdatedBroadcasts();
17881            info.sendSystemPackageAppearedBroadcasts();
17882        }
17883        // Force a gc here.
17884        Runtime.getRuntime().gc();
17885        // Delete the resources here after sending the broadcast to let
17886        // other processes clean up before deleting resources.
17887        if (info.args != null) {
17888            synchronized (mInstallLock) {
17889                info.args.doPostDeleteLI(true);
17890            }
17891        }
17892
17893        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17894    }
17895
17896    static class PackageRemovedInfo {
17897        final PackageSender packageSender;
17898        String removedPackage;
17899        String installerPackageName;
17900        int uid = -1;
17901        int removedAppId = -1;
17902        int[] origUsers;
17903        int[] removedUsers = null;
17904        int[] broadcastUsers = null;
17905        int[] instantUserIds = null;
17906        SparseArray<Integer> installReasons;
17907        boolean isRemovedPackageSystemUpdate = false;
17908        boolean isUpdate;
17909        boolean dataRemoved;
17910        boolean removedForAllUsers;
17911        boolean isStaticSharedLib;
17912        // Clean up resources deleted packages.
17913        InstallArgs args = null;
17914        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17915        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17916
17917        PackageRemovedInfo(PackageSender packageSender) {
17918            this.packageSender = packageSender;
17919        }
17920
17921        void sendPackageRemovedBroadcasts(boolean killApp) {
17922            sendPackageRemovedBroadcastInternal(killApp);
17923            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17924            for (int i = 0; i < childCount; i++) {
17925                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17926                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17927            }
17928        }
17929
17930        void sendSystemPackageUpdatedBroadcasts() {
17931            if (isRemovedPackageSystemUpdate) {
17932                sendSystemPackageUpdatedBroadcastsInternal();
17933                final int childCount = (removedChildPackages != null)
17934                        ? removedChildPackages.size() : 0;
17935                for (int i = 0; i < childCount; i++) {
17936                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17937                    if (childInfo.isRemovedPackageSystemUpdate) {
17938                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17939                    }
17940                }
17941            }
17942        }
17943
17944        void sendSystemPackageAppearedBroadcasts() {
17945            final int packageCount = (appearedChildPackages != null)
17946                    ? appearedChildPackages.size() : 0;
17947            for (int i = 0; i < packageCount; i++) {
17948                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17949                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17950                    true /*sendBootCompleted*/, false /*startReceiver*/,
17951                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
17952            }
17953        }
17954
17955        private void sendSystemPackageUpdatedBroadcastsInternal() {
17956            Bundle extras = new Bundle(2);
17957            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17958            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17959            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17960                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17961            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17962                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17963            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17964                null, null, 0, removedPackage, null, null, null);
17965            if (installerPackageName != null) {
17966                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17967                        removedPackage, extras, 0 /*flags*/,
17968                        installerPackageName, null, null, null);
17969                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17970                        removedPackage, extras, 0 /*flags*/,
17971                        installerPackageName, null, null, null);
17972            }
17973        }
17974
17975        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17976            // Don't send static shared library removal broadcasts as these
17977            // libs are visible only the the apps that depend on them an one
17978            // cannot remove the library if it has a dependency.
17979            if (isStaticSharedLib) {
17980                return;
17981            }
17982            Bundle extras = new Bundle(2);
17983            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17984            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17985            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17986            if (isUpdate || isRemovedPackageSystemUpdate) {
17987                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17988            }
17989            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17990            if (removedPackage != null) {
17991                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17992                    removedPackage, extras, 0, null /*targetPackage*/, null,
17993                    broadcastUsers, instantUserIds);
17994                if (installerPackageName != null) {
17995                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17996                            removedPackage, extras, 0 /*flags*/,
17997                            installerPackageName, null, broadcastUsers, instantUserIds);
17998                }
17999                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18000                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18001                        removedPackage, extras,
18002                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18003                        null, null, broadcastUsers, instantUserIds);
18004                    packageSender.notifyPackageRemoved(removedPackage);
18005                }
18006            }
18007            if (removedAppId >= 0) {
18008                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18009                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18010                    null, null, broadcastUsers, instantUserIds);
18011            }
18012        }
18013
18014        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18015            removedUsers = userIds;
18016            if (removedUsers == null) {
18017                broadcastUsers = null;
18018                return;
18019            }
18020
18021            broadcastUsers = EMPTY_INT_ARRAY;
18022            instantUserIds = EMPTY_INT_ARRAY;
18023            for (int i = userIds.length - 1; i >= 0; --i) {
18024                final int userId = userIds[i];
18025                if (deletedPackageSetting.getInstantApp(userId)) {
18026                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18027                } else {
18028                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18029                }
18030            }
18031        }
18032    }
18033
18034    /*
18035     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18036     * flag is not set, the data directory is removed as well.
18037     * make sure this flag is set for partially installed apps. If not its meaningless to
18038     * delete a partially installed application.
18039     */
18040    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18041            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18042        String packageName = ps.name;
18043        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18044        // Retrieve object to delete permissions for shared user later on
18045        final PackageParser.Package deletedPkg;
18046        final PackageSetting deletedPs;
18047        // reader
18048        synchronized (mPackages) {
18049            deletedPkg = mPackages.get(packageName);
18050            deletedPs = mSettings.mPackages.get(packageName);
18051            if (outInfo != null) {
18052                outInfo.removedPackage = packageName;
18053                outInfo.installerPackageName = ps.installerPackageName;
18054                outInfo.isStaticSharedLib = deletedPkg != null
18055                        && deletedPkg.staticSharedLibName != null;
18056                outInfo.populateUsers(deletedPs == null ? null
18057                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18058            }
18059        }
18060
18061        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18062
18063        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18064            final PackageParser.Package resolvedPkg;
18065            if (deletedPkg != null) {
18066                resolvedPkg = deletedPkg;
18067            } else {
18068                // We don't have a parsed package when it lives on an ejected
18069                // adopted storage device, so fake something together
18070                resolvedPkg = new PackageParser.Package(ps.name);
18071                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18072            }
18073            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18074                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18075            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18076            if (outInfo != null) {
18077                outInfo.dataRemoved = true;
18078            }
18079            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18080        }
18081
18082        int removedAppId = -1;
18083
18084        // writer
18085        synchronized (mPackages) {
18086            boolean installedStateChanged = false;
18087            if (deletedPs != null) {
18088                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18089                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18090                    clearDefaultBrowserIfNeeded(packageName);
18091                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18092                    removedAppId = mSettings.removePackageLPw(packageName);
18093                    if (outInfo != null) {
18094                        outInfo.removedAppId = removedAppId;
18095                    }
18096                    mPermissionManager.updatePermissions(
18097                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18098                    if (deletedPs.sharedUser != null) {
18099                        // Remove permissions associated with package. Since runtime
18100                        // permissions are per user we have to kill the removed package
18101                        // or packages running under the shared user of the removed
18102                        // package if revoking the permissions requested only by the removed
18103                        // package is successful and this causes a change in gids.
18104                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18105                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18106                                    userId);
18107                            if (userIdToKill == UserHandle.USER_ALL
18108                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18109                                // If gids changed for this user, kill all affected packages.
18110                                mHandler.post(new Runnable() {
18111                                    @Override
18112                                    public void run() {
18113                                        // This has to happen with no lock held.
18114                                        killApplication(deletedPs.name, deletedPs.appId,
18115                                                KILL_APP_REASON_GIDS_CHANGED);
18116                                    }
18117                                });
18118                                break;
18119                            }
18120                        }
18121                    }
18122                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18123                }
18124                // make sure to preserve per-user disabled state if this removal was just
18125                // a downgrade of a system app to the factory package
18126                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18127                    if (DEBUG_REMOVE) {
18128                        Slog.d(TAG, "Propagating install state across downgrade");
18129                    }
18130                    for (int userId : allUserHandles) {
18131                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18132                        if (DEBUG_REMOVE) {
18133                            Slog.d(TAG, "    user " + userId + " => " + installed);
18134                        }
18135                        if (installed != ps.getInstalled(userId)) {
18136                            installedStateChanged = true;
18137                        }
18138                        ps.setInstalled(installed, userId);
18139                    }
18140                }
18141            }
18142            // can downgrade to reader
18143            if (writeSettings) {
18144                // Save settings now
18145                mSettings.writeLPr();
18146            }
18147            if (installedStateChanged) {
18148                mSettings.writeKernelMappingLPr(ps);
18149            }
18150        }
18151        if (removedAppId != -1) {
18152            // A user ID was deleted here. Go through all users and remove it
18153            // from KeyStore.
18154            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18155        }
18156    }
18157
18158    static boolean locationIsPrivileged(String path) {
18159        try {
18160            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18161            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18162            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18163            return path.startsWith(privilegedAppDir.getCanonicalPath())
18164                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18165                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18166        } catch (IOException e) {
18167            Slog.e(TAG, "Unable to access code path " + path);
18168        }
18169        return false;
18170    }
18171
18172    static boolean locationIsOem(String path) {
18173        try {
18174            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18175        } catch (IOException e) {
18176            Slog.e(TAG, "Unable to access code path " + path);
18177        }
18178        return false;
18179    }
18180
18181    static boolean locationIsVendor(String path) {
18182        try {
18183            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
18184        } catch (IOException e) {
18185            Slog.e(TAG, "Unable to access code path " + path);
18186        }
18187        return false;
18188    }
18189
18190    static boolean locationIsProduct(String path) {
18191        try {
18192            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18193        } catch (IOException e) {
18194            Slog.e(TAG, "Unable to access code path " + path);
18195        }
18196        return false;
18197    }
18198
18199    /*
18200     * Tries to delete system package.
18201     */
18202    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18203            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18204            boolean writeSettings) {
18205        if (deletedPs.parentPackageName != null) {
18206            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18207            return false;
18208        }
18209
18210        final boolean applyUserRestrictions
18211                = (allUserHandles != null) && (outInfo.origUsers != null);
18212        final PackageSetting disabledPs;
18213        // Confirm if the system package has been updated
18214        // An updated system app can be deleted. This will also have to restore
18215        // the system pkg from system partition
18216        // reader
18217        synchronized (mPackages) {
18218            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18219        }
18220
18221        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18222                + " disabledPs=" + disabledPs);
18223
18224        if (disabledPs == null) {
18225            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18226            return false;
18227        } else if (DEBUG_REMOVE) {
18228            Slog.d(TAG, "Deleting system pkg from data partition");
18229        }
18230
18231        if (DEBUG_REMOVE) {
18232            if (applyUserRestrictions) {
18233                Slog.d(TAG, "Remembering install states:");
18234                for (int userId : allUserHandles) {
18235                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18236                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18237                }
18238            }
18239        }
18240
18241        // Delete the updated package
18242        outInfo.isRemovedPackageSystemUpdate = true;
18243        if (outInfo.removedChildPackages != null) {
18244            final int childCount = (deletedPs.childPackageNames != null)
18245                    ? deletedPs.childPackageNames.size() : 0;
18246            for (int i = 0; i < childCount; i++) {
18247                String childPackageName = deletedPs.childPackageNames.get(i);
18248                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18249                        .contains(childPackageName)) {
18250                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18251                            childPackageName);
18252                    if (childInfo != null) {
18253                        childInfo.isRemovedPackageSystemUpdate = true;
18254                    }
18255                }
18256            }
18257        }
18258
18259        if (disabledPs.versionCode < deletedPs.versionCode) {
18260            // Delete data for downgrades
18261            flags &= ~PackageManager.DELETE_KEEP_DATA;
18262        } else {
18263            // Preserve data by setting flag
18264            flags |= PackageManager.DELETE_KEEP_DATA;
18265        }
18266
18267        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18268                outInfo, writeSettings, disabledPs.pkg);
18269        if (!ret) {
18270            return false;
18271        }
18272
18273        // writer
18274        synchronized (mPackages) {
18275            // NOTE: The system package always needs to be enabled; even if it's for
18276            // a compressed stub. If we don't, installing the system package fails
18277            // during scan [scanning checks the disabled packages]. We will reverse
18278            // this later, after we've "installed" the stub.
18279            // Reinstate the old system package
18280            enableSystemPackageLPw(disabledPs.pkg);
18281            // Remove any native libraries from the upgraded package.
18282            removeNativeBinariesLI(deletedPs);
18283        }
18284
18285        // Install the system package
18286        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18287        try {
18288            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18289                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18290        } catch (PackageManagerException e) {
18291            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18292                    + e.getMessage());
18293            return false;
18294        } finally {
18295            if (disabledPs.pkg.isStub) {
18296                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18297            }
18298        }
18299        return true;
18300    }
18301
18302    /**
18303     * Installs a package that's already on the system partition.
18304     */
18305    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18306            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18307            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18308                    throws PackageManagerException {
18309        @ParseFlags int parseFlags =
18310                mDefParseFlags
18311                | PackageParser.PARSE_MUST_BE_APK
18312                | PackageParser.PARSE_IS_SYSTEM_DIR;
18313        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18314        if (isPrivileged || locationIsPrivileged(codePathString)) {
18315            scanFlags |= SCAN_AS_PRIVILEGED;
18316        }
18317        if (locationIsOem(codePathString)) {
18318            scanFlags |= SCAN_AS_OEM;
18319        }
18320        if (locationIsVendor(codePathString)) {
18321            scanFlags |= SCAN_AS_VENDOR;
18322        }
18323        if (locationIsProduct(codePathString)) {
18324            scanFlags |= SCAN_AS_PRODUCT;
18325        }
18326
18327        final File codePath = new File(codePathString);
18328        final PackageParser.Package pkg =
18329                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18330
18331        try {
18332            // update shared libraries for the newly re-installed system package
18333            updateSharedLibrariesLPr(pkg, null);
18334        } catch (PackageManagerException e) {
18335            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18336        }
18337
18338        prepareAppDataAfterInstallLIF(pkg);
18339
18340        // writer
18341        synchronized (mPackages) {
18342            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18343
18344            // Propagate the permissions state as we do not want to drop on the floor
18345            // runtime permissions. The update permissions method below will take
18346            // care of removing obsolete permissions and grant install permissions.
18347            if (origPermissionState != null) {
18348                ps.getPermissionsState().copyFrom(origPermissionState);
18349            }
18350            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18351                    mPermissionCallback);
18352
18353            final boolean applyUserRestrictions
18354                    = (allUserHandles != null) && (origUserHandles != null);
18355            if (applyUserRestrictions) {
18356                boolean installedStateChanged = false;
18357                if (DEBUG_REMOVE) {
18358                    Slog.d(TAG, "Propagating install state across reinstall");
18359                }
18360                for (int userId : allUserHandles) {
18361                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18362                    if (DEBUG_REMOVE) {
18363                        Slog.d(TAG, "    user " + userId + " => " + installed);
18364                    }
18365                    if (installed != ps.getInstalled(userId)) {
18366                        installedStateChanged = true;
18367                    }
18368                    ps.setInstalled(installed, userId);
18369
18370                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18371                }
18372                // Regardless of writeSettings we need to ensure that this restriction
18373                // state propagation is persisted
18374                mSettings.writeAllUsersPackageRestrictionsLPr();
18375                if (installedStateChanged) {
18376                    mSettings.writeKernelMappingLPr(ps);
18377                }
18378            }
18379            // can downgrade to reader here
18380            if (writeSettings) {
18381                mSettings.writeLPr();
18382            }
18383        }
18384        return pkg;
18385    }
18386
18387    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18388            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18389            PackageRemovedInfo outInfo, boolean writeSettings,
18390            PackageParser.Package replacingPackage) {
18391        synchronized (mPackages) {
18392            if (outInfo != null) {
18393                outInfo.uid = ps.appId;
18394            }
18395
18396            if (outInfo != null && outInfo.removedChildPackages != null) {
18397                final int childCount = (ps.childPackageNames != null)
18398                        ? ps.childPackageNames.size() : 0;
18399                for (int i = 0; i < childCount; i++) {
18400                    String childPackageName = ps.childPackageNames.get(i);
18401                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18402                    if (childPs == null) {
18403                        return false;
18404                    }
18405                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18406                            childPackageName);
18407                    if (childInfo != null) {
18408                        childInfo.uid = childPs.appId;
18409                    }
18410                }
18411            }
18412        }
18413
18414        // Delete package data from internal structures and also remove data if flag is set
18415        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18416
18417        // Delete the child packages data
18418        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18419        for (int i = 0; i < childCount; i++) {
18420            PackageSetting childPs;
18421            synchronized (mPackages) {
18422                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18423            }
18424            if (childPs != null) {
18425                PackageRemovedInfo childOutInfo = (outInfo != null
18426                        && outInfo.removedChildPackages != null)
18427                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18428                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18429                        && (replacingPackage != null
18430                        && !replacingPackage.hasChildPackage(childPs.name))
18431                        ? flags & ~DELETE_KEEP_DATA : flags;
18432                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18433                        deleteFlags, writeSettings);
18434            }
18435        }
18436
18437        // Delete application code and resources only for parent packages
18438        if (ps.parentPackageName == null) {
18439            if (deleteCodeAndResources && (outInfo != null)) {
18440                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18441                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18442                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18443            }
18444        }
18445
18446        return true;
18447    }
18448
18449    @Override
18450    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18451            int userId) {
18452        mContext.enforceCallingOrSelfPermission(
18453                android.Manifest.permission.DELETE_PACKAGES, null);
18454        synchronized (mPackages) {
18455            // Cannot block uninstall of static shared libs as they are
18456            // considered a part of the using app (emulating static linking).
18457            // Also static libs are installed always on internal storage.
18458            PackageParser.Package pkg = mPackages.get(packageName);
18459            if (pkg != null && pkg.staticSharedLibName != null) {
18460                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18461                        + " providing static shared library: " + pkg.staticSharedLibName);
18462                return false;
18463            }
18464            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18465            mSettings.writePackageRestrictionsLPr(userId);
18466        }
18467        return true;
18468    }
18469
18470    @Override
18471    public boolean getBlockUninstallForUser(String packageName, int userId) {
18472        synchronized (mPackages) {
18473            final PackageSetting ps = mSettings.mPackages.get(packageName);
18474            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18475                return false;
18476            }
18477            return mSettings.getBlockUninstallLPr(userId, packageName);
18478        }
18479    }
18480
18481    @Override
18482    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18483        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18484        synchronized (mPackages) {
18485            PackageSetting ps = mSettings.mPackages.get(packageName);
18486            if (ps == null) {
18487                Log.w(TAG, "Package doesn't exist: " + packageName);
18488                return false;
18489            }
18490            if (systemUserApp) {
18491                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18492            } else {
18493                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18494            }
18495            mSettings.writeLPr();
18496        }
18497        return true;
18498    }
18499
18500    /*
18501     * This method handles package deletion in general
18502     */
18503    private boolean deletePackageLIF(String packageName, UserHandle user,
18504            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18505            PackageRemovedInfo outInfo, boolean writeSettings,
18506            PackageParser.Package replacingPackage) {
18507        if (packageName == null) {
18508            Slog.w(TAG, "Attempt to delete null packageName.");
18509            return false;
18510        }
18511
18512        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18513
18514        PackageSetting ps;
18515        synchronized (mPackages) {
18516            ps = mSettings.mPackages.get(packageName);
18517            if (ps == null) {
18518                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18519                return false;
18520            }
18521
18522            if (ps.parentPackageName != null && (!isSystemApp(ps)
18523                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18524                if (DEBUG_REMOVE) {
18525                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18526                            + ((user == null) ? UserHandle.USER_ALL : user));
18527                }
18528                final int removedUserId = (user != null) ? user.getIdentifier()
18529                        : UserHandle.USER_ALL;
18530                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18531                    return false;
18532                }
18533                markPackageUninstalledForUserLPw(ps, user);
18534                scheduleWritePackageRestrictionsLocked(user);
18535                return true;
18536            }
18537        }
18538
18539        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18540                && user.getIdentifier() != UserHandle.USER_ALL)) {
18541            // The caller is asking that the package only be deleted for a single
18542            // user.  To do this, we just mark its uninstalled state and delete
18543            // its data. If this is a system app, we only allow this to happen if
18544            // they have set the special DELETE_SYSTEM_APP which requests different
18545            // semantics than normal for uninstalling system apps.
18546            markPackageUninstalledForUserLPw(ps, user);
18547
18548            if (!isSystemApp(ps)) {
18549                // Do not uninstall the APK if an app should be cached
18550                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18551                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18552                    // Other user still have this package installed, so all
18553                    // we need to do is clear this user's data and save that
18554                    // it is uninstalled.
18555                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18556                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18557                        return false;
18558                    }
18559                    scheduleWritePackageRestrictionsLocked(user);
18560                    return true;
18561                } else {
18562                    // We need to set it back to 'installed' so the uninstall
18563                    // broadcasts will be sent correctly.
18564                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18565                    ps.setInstalled(true, user.getIdentifier());
18566                    mSettings.writeKernelMappingLPr(ps);
18567                }
18568            } else {
18569                // This is a system app, so we assume that the
18570                // other users still have this package installed, so all
18571                // we need to do is clear this user's data and save that
18572                // it is uninstalled.
18573                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18574                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18575                    return false;
18576                }
18577                scheduleWritePackageRestrictionsLocked(user);
18578                return true;
18579            }
18580        }
18581
18582        // If we are deleting a composite package for all users, keep track
18583        // of result for each child.
18584        if (ps.childPackageNames != null && outInfo != null) {
18585            synchronized (mPackages) {
18586                final int childCount = ps.childPackageNames.size();
18587                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18588                for (int i = 0; i < childCount; i++) {
18589                    String childPackageName = ps.childPackageNames.get(i);
18590                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18591                    childInfo.removedPackage = childPackageName;
18592                    childInfo.installerPackageName = ps.installerPackageName;
18593                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18594                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18595                    if (childPs != null) {
18596                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18597                    }
18598                }
18599            }
18600        }
18601
18602        boolean ret = false;
18603        if (isSystemApp(ps)) {
18604            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18605            // When an updated system application is deleted we delete the existing resources
18606            // as well and fall back to existing code in system partition
18607            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18608        } else {
18609            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18610            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18611                    outInfo, writeSettings, replacingPackage);
18612        }
18613
18614        // Take a note whether we deleted the package for all users
18615        if (outInfo != null) {
18616            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18617            if (outInfo.removedChildPackages != null) {
18618                synchronized (mPackages) {
18619                    final int childCount = outInfo.removedChildPackages.size();
18620                    for (int i = 0; i < childCount; i++) {
18621                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18622                        if (childInfo != null) {
18623                            childInfo.removedForAllUsers = mPackages.get(
18624                                    childInfo.removedPackage) == null;
18625                        }
18626                    }
18627                }
18628            }
18629            // If we uninstalled an update to a system app there may be some
18630            // child packages that appeared as they are declared in the system
18631            // app but were not declared in the update.
18632            if (isSystemApp(ps)) {
18633                synchronized (mPackages) {
18634                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18635                    final int childCount = (updatedPs.childPackageNames != null)
18636                            ? updatedPs.childPackageNames.size() : 0;
18637                    for (int i = 0; i < childCount; i++) {
18638                        String childPackageName = updatedPs.childPackageNames.get(i);
18639                        if (outInfo.removedChildPackages == null
18640                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18641                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18642                            if (childPs == null) {
18643                                continue;
18644                            }
18645                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18646                            installRes.name = childPackageName;
18647                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18648                            installRes.pkg = mPackages.get(childPackageName);
18649                            installRes.uid = childPs.pkg.applicationInfo.uid;
18650                            if (outInfo.appearedChildPackages == null) {
18651                                outInfo.appearedChildPackages = new ArrayMap<>();
18652                            }
18653                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18654                        }
18655                    }
18656                }
18657            }
18658        }
18659
18660        return ret;
18661    }
18662
18663    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18664        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18665                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18666        for (int nextUserId : userIds) {
18667            if (DEBUG_REMOVE) {
18668                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18669            }
18670            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18671                    false /*installed*/,
18672                    true /*stopped*/,
18673                    true /*notLaunched*/,
18674                    false /*hidden*/,
18675                    false /*suspended*/,
18676                    false /*instantApp*/,
18677                    false /*virtualPreload*/,
18678                    null /*lastDisableAppCaller*/,
18679                    null /*enabledComponents*/,
18680                    null /*disabledComponents*/,
18681                    ps.readUserState(nextUserId).domainVerificationStatus,
18682                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18683                    null /*harmfulAppWarning*/);
18684        }
18685        mSettings.writeKernelMappingLPr(ps);
18686    }
18687
18688    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18689            PackageRemovedInfo outInfo) {
18690        final PackageParser.Package pkg;
18691        synchronized (mPackages) {
18692            pkg = mPackages.get(ps.name);
18693        }
18694
18695        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18696                : new int[] {userId};
18697        for (int nextUserId : userIds) {
18698            if (DEBUG_REMOVE) {
18699                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18700                        + nextUserId);
18701            }
18702
18703            destroyAppDataLIF(pkg, userId,
18704                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18705            destroyAppProfilesLIF(pkg, userId);
18706            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18707            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18708            schedulePackageCleaning(ps.name, nextUserId, false);
18709            synchronized (mPackages) {
18710                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18711                    scheduleWritePackageRestrictionsLocked(nextUserId);
18712                }
18713                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18714            }
18715        }
18716
18717        if (outInfo != null) {
18718            outInfo.removedPackage = ps.name;
18719            outInfo.installerPackageName = ps.installerPackageName;
18720            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18721            outInfo.removedAppId = ps.appId;
18722            outInfo.removedUsers = userIds;
18723            outInfo.broadcastUsers = userIds;
18724        }
18725
18726        return true;
18727    }
18728
18729    private final class ClearStorageConnection implements ServiceConnection {
18730        IMediaContainerService mContainerService;
18731
18732        @Override
18733        public void onServiceConnected(ComponentName name, IBinder service) {
18734            synchronized (this) {
18735                mContainerService = IMediaContainerService.Stub
18736                        .asInterface(Binder.allowBlocking(service));
18737                notifyAll();
18738            }
18739        }
18740
18741        @Override
18742        public void onServiceDisconnected(ComponentName name) {
18743        }
18744    }
18745
18746    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18747        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18748
18749        final boolean mounted;
18750        if (Environment.isExternalStorageEmulated()) {
18751            mounted = true;
18752        } else {
18753            final String status = Environment.getExternalStorageState();
18754
18755            mounted = status.equals(Environment.MEDIA_MOUNTED)
18756                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18757        }
18758
18759        if (!mounted) {
18760            return;
18761        }
18762
18763        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18764        int[] users;
18765        if (userId == UserHandle.USER_ALL) {
18766            users = sUserManager.getUserIds();
18767        } else {
18768            users = new int[] { userId };
18769        }
18770        final ClearStorageConnection conn = new ClearStorageConnection();
18771        if (mContext.bindServiceAsUser(
18772                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18773            try {
18774                for (int curUser : users) {
18775                    long timeout = SystemClock.uptimeMillis() + 5000;
18776                    synchronized (conn) {
18777                        long now;
18778                        while (conn.mContainerService == null &&
18779                                (now = SystemClock.uptimeMillis()) < timeout) {
18780                            try {
18781                                conn.wait(timeout - now);
18782                            } catch (InterruptedException e) {
18783                            }
18784                        }
18785                    }
18786                    if (conn.mContainerService == null) {
18787                        return;
18788                    }
18789
18790                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18791                    clearDirectory(conn.mContainerService,
18792                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18793                    if (allData) {
18794                        clearDirectory(conn.mContainerService,
18795                                userEnv.buildExternalStorageAppDataDirs(packageName));
18796                        clearDirectory(conn.mContainerService,
18797                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18798                    }
18799                }
18800            } finally {
18801                mContext.unbindService(conn);
18802            }
18803        }
18804    }
18805
18806    @Override
18807    public void clearApplicationProfileData(String packageName) {
18808        enforceSystemOrRoot("Only the system can clear all profile data");
18809
18810        final PackageParser.Package pkg;
18811        synchronized (mPackages) {
18812            pkg = mPackages.get(packageName);
18813        }
18814
18815        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18816            synchronized (mInstallLock) {
18817                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18818            }
18819        }
18820    }
18821
18822    @Override
18823    public void clearApplicationUserData(final String packageName,
18824            final IPackageDataObserver observer, final int userId) {
18825        mContext.enforceCallingOrSelfPermission(
18826                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18827
18828        final int callingUid = Binder.getCallingUid();
18829        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18830                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18831
18832        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18833        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18834        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18835            throw new SecurityException("Cannot clear data for a protected package: "
18836                    + packageName);
18837        }
18838        // Queue up an async operation since the package deletion may take a little while.
18839        mHandler.post(new Runnable() {
18840            public void run() {
18841                mHandler.removeCallbacks(this);
18842                final boolean succeeded;
18843                if (!filterApp) {
18844                    try (PackageFreezer freezer = freezePackage(packageName,
18845                            "clearApplicationUserData")) {
18846                        synchronized (mInstallLock) {
18847                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18848                        }
18849                        clearExternalStorageDataSync(packageName, userId, true);
18850                        synchronized (mPackages) {
18851                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18852                                    packageName, userId);
18853                        }
18854                    }
18855                    if (succeeded) {
18856                        // invoke DeviceStorageMonitor's update method to clear any notifications
18857                        DeviceStorageMonitorInternal dsm = LocalServices
18858                                .getService(DeviceStorageMonitorInternal.class);
18859                        if (dsm != null) {
18860                            dsm.checkMemory();
18861                        }
18862                    }
18863                } else {
18864                    succeeded = false;
18865                }
18866                if (observer != null) {
18867                    try {
18868                        observer.onRemoveCompleted(packageName, succeeded);
18869                    } catch (RemoteException e) {
18870                        Log.i(TAG, "Observer no longer exists.");
18871                    }
18872                } //end if observer
18873            } //end run
18874        });
18875    }
18876
18877    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18878        if (packageName == null) {
18879            Slog.w(TAG, "Attempt to delete null packageName.");
18880            return false;
18881        }
18882
18883        // Try finding details about the requested package
18884        PackageParser.Package pkg;
18885        synchronized (mPackages) {
18886            pkg = mPackages.get(packageName);
18887            if (pkg == null) {
18888                final PackageSetting ps = mSettings.mPackages.get(packageName);
18889                if (ps != null) {
18890                    pkg = ps.pkg;
18891                }
18892            }
18893
18894            if (pkg == null) {
18895                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18896                return false;
18897            }
18898
18899            PackageSetting ps = (PackageSetting) pkg.mExtras;
18900            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18901        }
18902
18903        clearAppDataLIF(pkg, userId,
18904                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18905
18906        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18907        removeKeystoreDataIfNeeded(userId, appId);
18908
18909        UserManagerInternal umInternal = getUserManagerInternal();
18910        final int flags;
18911        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18912            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18913        } else if (umInternal.isUserRunning(userId)) {
18914            flags = StorageManager.FLAG_STORAGE_DE;
18915        } else {
18916            flags = 0;
18917        }
18918        prepareAppDataContentsLIF(pkg, userId, flags);
18919
18920        return true;
18921    }
18922
18923    /**
18924     * Reverts user permission state changes (permissions and flags) in
18925     * all packages for a given user.
18926     *
18927     * @param userId The device user for which to do a reset.
18928     */
18929    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18930        final int packageCount = mPackages.size();
18931        for (int i = 0; i < packageCount; i++) {
18932            PackageParser.Package pkg = mPackages.valueAt(i);
18933            PackageSetting ps = (PackageSetting) pkg.mExtras;
18934            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18935        }
18936    }
18937
18938    private void resetNetworkPolicies(int userId) {
18939        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18940    }
18941
18942    /**
18943     * Reverts user permission state changes (permissions and flags).
18944     *
18945     * @param ps The package for which to reset.
18946     * @param userId The device user for which to do a reset.
18947     */
18948    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18949            final PackageSetting ps, final int userId) {
18950        if (ps.pkg == null) {
18951            return;
18952        }
18953
18954        // These are flags that can change base on user actions.
18955        final int userSettableMask = FLAG_PERMISSION_USER_SET
18956                | FLAG_PERMISSION_USER_FIXED
18957                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18958                | FLAG_PERMISSION_REVIEW_REQUIRED;
18959
18960        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18961                | FLAG_PERMISSION_POLICY_FIXED;
18962
18963        boolean writeInstallPermissions = false;
18964        boolean writeRuntimePermissions = false;
18965
18966        final int permissionCount = ps.pkg.requestedPermissions.size();
18967        for (int i = 0; i < permissionCount; i++) {
18968            final String permName = ps.pkg.requestedPermissions.get(i);
18969            final BasePermission bp =
18970                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18971            if (bp == null) {
18972                continue;
18973            }
18974
18975            // If shared user we just reset the state to which only this app contributed.
18976            if (ps.sharedUser != null) {
18977                boolean used = false;
18978                final int packageCount = ps.sharedUser.packages.size();
18979                for (int j = 0; j < packageCount; j++) {
18980                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18981                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18982                            && pkg.pkg.requestedPermissions.contains(permName)) {
18983                        used = true;
18984                        break;
18985                    }
18986                }
18987                if (used) {
18988                    continue;
18989                }
18990            }
18991
18992            final PermissionsState permissionsState = ps.getPermissionsState();
18993
18994            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
18995
18996            // Always clear the user settable flags.
18997            final boolean hasInstallState =
18998                    permissionsState.getInstallPermissionState(permName) != null;
18999            // If permission review is enabled and this is a legacy app, mark the
19000            // permission as requiring a review as this is the initial state.
19001            int flags = 0;
19002            if (mSettings.mPermissions.mPermissionReviewRequired
19003                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19004                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19005            }
19006            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19007                if (hasInstallState) {
19008                    writeInstallPermissions = true;
19009                } else {
19010                    writeRuntimePermissions = true;
19011                }
19012            }
19013
19014            // Below is only runtime permission handling.
19015            if (!bp.isRuntime()) {
19016                continue;
19017            }
19018
19019            // Never clobber system or policy.
19020            if ((oldFlags & policyOrSystemFlags) != 0) {
19021                continue;
19022            }
19023
19024            // If this permission was granted by default, make sure it is.
19025            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19026                if (permissionsState.grantRuntimePermission(bp, userId)
19027                        != PERMISSION_OPERATION_FAILURE) {
19028                    writeRuntimePermissions = true;
19029                }
19030            // If permission review is enabled the permissions for a legacy apps
19031            // are represented as constantly granted runtime ones, so don't revoke.
19032            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19033                // Otherwise, reset the permission.
19034                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19035                switch (revokeResult) {
19036                    case PERMISSION_OPERATION_SUCCESS:
19037                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19038                        writeRuntimePermissions = true;
19039                        final int appId = ps.appId;
19040                        mHandler.post(new Runnable() {
19041                            @Override
19042                            public void run() {
19043                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19044                            }
19045                        });
19046                    } break;
19047                }
19048            }
19049        }
19050
19051        // Synchronously write as we are taking permissions away.
19052        if (writeRuntimePermissions) {
19053            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19054        }
19055
19056        // Synchronously write as we are taking permissions away.
19057        if (writeInstallPermissions) {
19058            mSettings.writeLPr();
19059        }
19060    }
19061
19062    /**
19063     * Remove entries from the keystore daemon. Will only remove it if the
19064     * {@code appId} is valid.
19065     */
19066    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19067        if (appId < 0) {
19068            return;
19069        }
19070
19071        final KeyStore keyStore = KeyStore.getInstance();
19072        if (keyStore != null) {
19073            if (userId == UserHandle.USER_ALL) {
19074                for (final int individual : sUserManager.getUserIds()) {
19075                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19076                }
19077            } else {
19078                keyStore.clearUid(UserHandle.getUid(userId, appId));
19079            }
19080        } else {
19081            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19082        }
19083    }
19084
19085    @Override
19086    public void deleteApplicationCacheFiles(final String packageName,
19087            final IPackageDataObserver observer) {
19088        final int userId = UserHandle.getCallingUserId();
19089        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19090    }
19091
19092    @Override
19093    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19094            final IPackageDataObserver observer) {
19095        final int callingUid = Binder.getCallingUid();
19096        mContext.enforceCallingOrSelfPermission(
19097                android.Manifest.permission.DELETE_CACHE_FILES, null);
19098        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19099                /* requireFullPermission= */ true, /* checkShell= */ false,
19100                "delete application cache files");
19101        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19102                android.Manifest.permission.ACCESS_INSTANT_APPS);
19103
19104        final PackageParser.Package pkg;
19105        synchronized (mPackages) {
19106            pkg = mPackages.get(packageName);
19107        }
19108
19109        // Queue up an async operation since the package deletion may take a little while.
19110        mHandler.post(new Runnable() {
19111            public void run() {
19112                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19113                boolean doClearData = true;
19114                if (ps != null) {
19115                    final boolean targetIsInstantApp =
19116                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19117                    doClearData = !targetIsInstantApp
19118                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19119                }
19120                if (doClearData) {
19121                    synchronized (mInstallLock) {
19122                        final int flags = StorageManager.FLAG_STORAGE_DE
19123                                | StorageManager.FLAG_STORAGE_CE;
19124                        // We're only clearing cache files, so we don't care if the
19125                        // app is unfrozen and still able to run
19126                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19127                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19128                    }
19129                    clearExternalStorageDataSync(packageName, userId, false);
19130                }
19131                if (observer != null) {
19132                    try {
19133                        observer.onRemoveCompleted(packageName, true);
19134                    } catch (RemoteException e) {
19135                        Log.i(TAG, "Observer no longer exists.");
19136                    }
19137                }
19138            }
19139        });
19140    }
19141
19142    @Override
19143    public void getPackageSizeInfo(final String packageName, int userHandle,
19144            final IPackageStatsObserver observer) {
19145        throw new UnsupportedOperationException(
19146                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19147    }
19148
19149    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19150        final PackageSetting ps;
19151        synchronized (mPackages) {
19152            ps = mSettings.mPackages.get(packageName);
19153            if (ps == null) {
19154                Slog.w(TAG, "Failed to find settings for " + packageName);
19155                return false;
19156            }
19157        }
19158
19159        final String[] packageNames = { packageName };
19160        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19161        final String[] codePaths = { ps.codePathString };
19162
19163        try {
19164            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19165                    ps.appId, ceDataInodes, codePaths, stats);
19166
19167            // For now, ignore code size of packages on system partition
19168            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19169                stats.codeSize = 0;
19170            }
19171
19172            // External clients expect these to be tracked separately
19173            stats.dataSize -= stats.cacheSize;
19174
19175        } catch (InstallerException e) {
19176            Slog.w(TAG, String.valueOf(e));
19177            return false;
19178        }
19179
19180        return true;
19181    }
19182
19183    private int getUidTargetSdkVersionLockedLPr(int uid) {
19184        Object obj = mSettings.getUserIdLPr(uid);
19185        if (obj instanceof SharedUserSetting) {
19186            final SharedUserSetting sus = (SharedUserSetting) obj;
19187            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19188            final Iterator<PackageSetting> it = sus.packages.iterator();
19189            while (it.hasNext()) {
19190                final PackageSetting ps = it.next();
19191                if (ps.pkg != null) {
19192                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19193                    if (v < vers) vers = v;
19194                }
19195            }
19196            return vers;
19197        } else if (obj instanceof PackageSetting) {
19198            final PackageSetting ps = (PackageSetting) obj;
19199            if (ps.pkg != null) {
19200                return ps.pkg.applicationInfo.targetSdkVersion;
19201            }
19202        }
19203        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19204    }
19205
19206    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19207        final PackageParser.Package p = mPackages.get(packageName);
19208        if (p != null) {
19209            return p.applicationInfo.targetSdkVersion;
19210        }
19211        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19212    }
19213
19214    @Override
19215    public void addPreferredActivity(IntentFilter filter, int match,
19216            ComponentName[] set, ComponentName activity, int userId) {
19217        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19218                "Adding preferred");
19219    }
19220
19221    private void addPreferredActivityInternal(IntentFilter filter, int match,
19222            ComponentName[] set, ComponentName activity, boolean always, int userId,
19223            String opname) {
19224        // writer
19225        int callingUid = Binder.getCallingUid();
19226        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19227                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19228        if (filter.countActions() == 0) {
19229            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19230            return;
19231        }
19232        synchronized (mPackages) {
19233            if (mContext.checkCallingOrSelfPermission(
19234                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19235                    != PackageManager.PERMISSION_GRANTED) {
19236                if (getUidTargetSdkVersionLockedLPr(callingUid)
19237                        < Build.VERSION_CODES.FROYO) {
19238                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19239                            + callingUid);
19240                    return;
19241                }
19242                mContext.enforceCallingOrSelfPermission(
19243                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19244            }
19245
19246            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19247            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19248                    + userId + ":");
19249            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19250            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19251            scheduleWritePackageRestrictionsLocked(userId);
19252            postPreferredActivityChangedBroadcast(userId);
19253        }
19254    }
19255
19256    private void postPreferredActivityChangedBroadcast(int userId) {
19257        mHandler.post(() -> {
19258            final IActivityManager am = ActivityManager.getService();
19259            if (am == null) {
19260                return;
19261            }
19262
19263            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19264            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19265            try {
19266                am.broadcastIntent(null, intent, null, null,
19267                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19268                        null, false, false, userId);
19269            } catch (RemoteException e) {
19270            }
19271        });
19272    }
19273
19274    @Override
19275    public void replacePreferredActivity(IntentFilter filter, int match,
19276            ComponentName[] set, ComponentName activity, int userId) {
19277        if (filter.countActions() != 1) {
19278            throw new IllegalArgumentException(
19279                    "replacePreferredActivity expects filter to have only 1 action.");
19280        }
19281        if (filter.countDataAuthorities() != 0
19282                || filter.countDataPaths() != 0
19283                || filter.countDataSchemes() > 1
19284                || filter.countDataTypes() != 0) {
19285            throw new IllegalArgumentException(
19286                    "replacePreferredActivity expects filter to have no data authorities, " +
19287                    "paths, or types; and at most one scheme.");
19288        }
19289
19290        final int callingUid = Binder.getCallingUid();
19291        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19292                true /* requireFullPermission */, false /* checkShell */,
19293                "replace preferred activity");
19294        synchronized (mPackages) {
19295            if (mContext.checkCallingOrSelfPermission(
19296                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19297                    != PackageManager.PERMISSION_GRANTED) {
19298                if (getUidTargetSdkVersionLockedLPr(callingUid)
19299                        < Build.VERSION_CODES.FROYO) {
19300                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19301                            + Binder.getCallingUid());
19302                    return;
19303                }
19304                mContext.enforceCallingOrSelfPermission(
19305                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19306            }
19307
19308            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19309            if (pir != null) {
19310                // Get all of the existing entries that exactly match this filter.
19311                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19312                if (existing != null && existing.size() == 1) {
19313                    PreferredActivity cur = existing.get(0);
19314                    if (DEBUG_PREFERRED) {
19315                        Slog.i(TAG, "Checking replace of preferred:");
19316                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19317                        if (!cur.mPref.mAlways) {
19318                            Slog.i(TAG, "  -- CUR; not mAlways!");
19319                        } else {
19320                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19321                            Slog.i(TAG, "  -- CUR: mSet="
19322                                    + Arrays.toString(cur.mPref.mSetComponents));
19323                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19324                            Slog.i(TAG, "  -- NEW: mMatch="
19325                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19326                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19327                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19328                        }
19329                    }
19330                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19331                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19332                            && cur.mPref.sameSet(set)) {
19333                        // Setting the preferred activity to what it happens to be already
19334                        if (DEBUG_PREFERRED) {
19335                            Slog.i(TAG, "Replacing with same preferred activity "
19336                                    + cur.mPref.mShortComponent + " for user "
19337                                    + userId + ":");
19338                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19339                        }
19340                        return;
19341                    }
19342                }
19343
19344                if (existing != null) {
19345                    if (DEBUG_PREFERRED) {
19346                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19347                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19348                    }
19349                    for (int i = 0; i < existing.size(); i++) {
19350                        PreferredActivity pa = existing.get(i);
19351                        if (DEBUG_PREFERRED) {
19352                            Slog.i(TAG, "Removing existing preferred activity "
19353                                    + pa.mPref.mComponent + ":");
19354                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19355                        }
19356                        pir.removeFilter(pa);
19357                    }
19358                }
19359            }
19360            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19361                    "Replacing preferred");
19362        }
19363    }
19364
19365    @Override
19366    public void clearPackagePreferredActivities(String packageName) {
19367        final int callingUid = Binder.getCallingUid();
19368        if (getInstantAppPackageName(callingUid) != null) {
19369            return;
19370        }
19371        // writer
19372        synchronized (mPackages) {
19373            PackageParser.Package pkg = mPackages.get(packageName);
19374            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19375                if (mContext.checkCallingOrSelfPermission(
19376                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19377                        != PackageManager.PERMISSION_GRANTED) {
19378                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19379                            < Build.VERSION_CODES.FROYO) {
19380                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19381                                + callingUid);
19382                        return;
19383                    }
19384                    mContext.enforceCallingOrSelfPermission(
19385                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19386                }
19387            }
19388            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19389            if (ps != null
19390                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19391                return;
19392            }
19393            int user = UserHandle.getCallingUserId();
19394            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19395                scheduleWritePackageRestrictionsLocked(user);
19396            }
19397        }
19398    }
19399
19400    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19401    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19402        ArrayList<PreferredActivity> removed = null;
19403        boolean changed = false;
19404        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19405            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19406            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19407            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19408                continue;
19409            }
19410            Iterator<PreferredActivity> it = pir.filterIterator();
19411            while (it.hasNext()) {
19412                PreferredActivity pa = it.next();
19413                // Mark entry for removal only if it matches the package name
19414                // and the entry is of type "always".
19415                if (packageName == null ||
19416                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19417                                && pa.mPref.mAlways)) {
19418                    if (removed == null) {
19419                        removed = new ArrayList<PreferredActivity>();
19420                    }
19421                    removed.add(pa);
19422                }
19423            }
19424            if (removed != null) {
19425                for (int j=0; j<removed.size(); j++) {
19426                    PreferredActivity pa = removed.get(j);
19427                    pir.removeFilter(pa);
19428                }
19429                changed = true;
19430            }
19431        }
19432        if (changed) {
19433            postPreferredActivityChangedBroadcast(userId);
19434        }
19435        return changed;
19436    }
19437
19438    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19439    private void clearIntentFilterVerificationsLPw(int userId) {
19440        final int packageCount = mPackages.size();
19441        for (int i = 0; i < packageCount; i++) {
19442            PackageParser.Package pkg = mPackages.valueAt(i);
19443            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19444        }
19445    }
19446
19447    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19448    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19449        if (userId == UserHandle.USER_ALL) {
19450            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19451                    sUserManager.getUserIds())) {
19452                for (int oneUserId : sUserManager.getUserIds()) {
19453                    scheduleWritePackageRestrictionsLocked(oneUserId);
19454                }
19455            }
19456        } else {
19457            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19458                scheduleWritePackageRestrictionsLocked(userId);
19459            }
19460        }
19461    }
19462
19463    /** Clears state for all users, and touches intent filter verification policy */
19464    void clearDefaultBrowserIfNeeded(String packageName) {
19465        for (int oneUserId : sUserManager.getUserIds()) {
19466            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19467        }
19468    }
19469
19470    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19471        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19472        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19473            if (packageName.equals(defaultBrowserPackageName)) {
19474                setDefaultBrowserPackageName(null, userId);
19475            }
19476        }
19477    }
19478
19479    @Override
19480    public void resetApplicationPreferences(int userId) {
19481        mContext.enforceCallingOrSelfPermission(
19482                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19483        final long identity = Binder.clearCallingIdentity();
19484        // writer
19485        try {
19486            synchronized (mPackages) {
19487                clearPackagePreferredActivitiesLPw(null, userId);
19488                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19489                // TODO: We have to reset the default SMS and Phone. This requires
19490                // significant refactoring to keep all default apps in the package
19491                // manager (cleaner but more work) or have the services provide
19492                // callbacks to the package manager to request a default app reset.
19493                applyFactoryDefaultBrowserLPw(userId);
19494                clearIntentFilterVerificationsLPw(userId);
19495                primeDomainVerificationsLPw(userId);
19496                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19497                scheduleWritePackageRestrictionsLocked(userId);
19498            }
19499            resetNetworkPolicies(userId);
19500        } finally {
19501            Binder.restoreCallingIdentity(identity);
19502        }
19503    }
19504
19505    @Override
19506    public int getPreferredActivities(List<IntentFilter> outFilters,
19507            List<ComponentName> outActivities, String packageName) {
19508        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19509            return 0;
19510        }
19511        int num = 0;
19512        final int userId = UserHandle.getCallingUserId();
19513        // reader
19514        synchronized (mPackages) {
19515            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19516            if (pir != null) {
19517                final Iterator<PreferredActivity> it = pir.filterIterator();
19518                while (it.hasNext()) {
19519                    final PreferredActivity pa = it.next();
19520                    if (packageName == null
19521                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19522                                    && pa.mPref.mAlways)) {
19523                        if (outFilters != null) {
19524                            outFilters.add(new IntentFilter(pa));
19525                        }
19526                        if (outActivities != null) {
19527                            outActivities.add(pa.mPref.mComponent);
19528                        }
19529                    }
19530                }
19531            }
19532        }
19533
19534        return num;
19535    }
19536
19537    @Override
19538    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19539            int userId) {
19540        int callingUid = Binder.getCallingUid();
19541        if (callingUid != Process.SYSTEM_UID) {
19542            throw new SecurityException(
19543                    "addPersistentPreferredActivity can only be run by the system");
19544        }
19545        if (filter.countActions() == 0) {
19546            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19547            return;
19548        }
19549        synchronized (mPackages) {
19550            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19551                    ":");
19552            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19553            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19554                    new PersistentPreferredActivity(filter, activity));
19555            scheduleWritePackageRestrictionsLocked(userId);
19556            postPreferredActivityChangedBroadcast(userId);
19557        }
19558    }
19559
19560    @Override
19561    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19562        int callingUid = Binder.getCallingUid();
19563        if (callingUid != Process.SYSTEM_UID) {
19564            throw new SecurityException(
19565                    "clearPackagePersistentPreferredActivities can only be run by the system");
19566        }
19567        ArrayList<PersistentPreferredActivity> removed = null;
19568        boolean changed = false;
19569        synchronized (mPackages) {
19570            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19571                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19572                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19573                        .valueAt(i);
19574                if (userId != thisUserId) {
19575                    continue;
19576                }
19577                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19578                while (it.hasNext()) {
19579                    PersistentPreferredActivity ppa = it.next();
19580                    // Mark entry for removal only if it matches the package name.
19581                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19582                        if (removed == null) {
19583                            removed = new ArrayList<PersistentPreferredActivity>();
19584                        }
19585                        removed.add(ppa);
19586                    }
19587                }
19588                if (removed != null) {
19589                    for (int j=0; j<removed.size(); j++) {
19590                        PersistentPreferredActivity ppa = removed.get(j);
19591                        ppir.removeFilter(ppa);
19592                    }
19593                    changed = true;
19594                }
19595            }
19596
19597            if (changed) {
19598                scheduleWritePackageRestrictionsLocked(userId);
19599                postPreferredActivityChangedBroadcast(userId);
19600            }
19601        }
19602    }
19603
19604    /**
19605     * Common machinery for picking apart a restored XML blob and passing
19606     * it to a caller-supplied functor to be applied to the running system.
19607     */
19608    private void restoreFromXml(XmlPullParser parser, int userId,
19609            String expectedStartTag, BlobXmlRestorer functor)
19610            throws IOException, XmlPullParserException {
19611        int type;
19612        while ((type = parser.next()) != XmlPullParser.START_TAG
19613                && type != XmlPullParser.END_DOCUMENT) {
19614        }
19615        if (type != XmlPullParser.START_TAG) {
19616            // oops didn't find a start tag?!
19617            if (DEBUG_BACKUP) {
19618                Slog.e(TAG, "Didn't find start tag during restore");
19619            }
19620            return;
19621        }
19622Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19623        // this is supposed to be TAG_PREFERRED_BACKUP
19624        if (!expectedStartTag.equals(parser.getName())) {
19625            if (DEBUG_BACKUP) {
19626                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19627            }
19628            return;
19629        }
19630
19631        // skip interfering stuff, then we're aligned with the backing implementation
19632        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19633Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19634        functor.apply(parser, userId);
19635    }
19636
19637    private interface BlobXmlRestorer {
19638        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19639    }
19640
19641    /**
19642     * Non-Binder method, support for the backup/restore mechanism: write the
19643     * full set of preferred activities in its canonical XML format.  Returns the
19644     * XML output as a byte array, or null if there is none.
19645     */
19646    @Override
19647    public byte[] getPreferredActivityBackup(int userId) {
19648        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19649            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19650        }
19651
19652        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19653        try {
19654            final XmlSerializer serializer = new FastXmlSerializer();
19655            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19656            serializer.startDocument(null, true);
19657            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19658
19659            synchronized (mPackages) {
19660                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19661            }
19662
19663            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19664            serializer.endDocument();
19665            serializer.flush();
19666        } catch (Exception e) {
19667            if (DEBUG_BACKUP) {
19668                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19669            }
19670            return null;
19671        }
19672
19673        return dataStream.toByteArray();
19674    }
19675
19676    @Override
19677    public void restorePreferredActivities(byte[] backup, int userId) {
19678        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19679            throw new SecurityException("Only the system may call restorePreferredActivities()");
19680        }
19681
19682        try {
19683            final XmlPullParser parser = Xml.newPullParser();
19684            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19685            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19686                    new BlobXmlRestorer() {
19687                        @Override
19688                        public void apply(XmlPullParser parser, int userId)
19689                                throws XmlPullParserException, IOException {
19690                            synchronized (mPackages) {
19691                                mSettings.readPreferredActivitiesLPw(parser, userId);
19692                            }
19693                        }
19694                    } );
19695        } catch (Exception e) {
19696            if (DEBUG_BACKUP) {
19697                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19698            }
19699        }
19700    }
19701
19702    /**
19703     * Non-Binder method, support for the backup/restore mechanism: write the
19704     * default browser (etc) settings in its canonical XML format.  Returns the default
19705     * browser XML representation as a byte array, or null if there is none.
19706     */
19707    @Override
19708    public byte[] getDefaultAppsBackup(int userId) {
19709        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19710            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19711        }
19712
19713        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19714        try {
19715            final XmlSerializer serializer = new FastXmlSerializer();
19716            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19717            serializer.startDocument(null, true);
19718            serializer.startTag(null, TAG_DEFAULT_APPS);
19719
19720            synchronized (mPackages) {
19721                mSettings.writeDefaultAppsLPr(serializer, userId);
19722            }
19723
19724            serializer.endTag(null, TAG_DEFAULT_APPS);
19725            serializer.endDocument();
19726            serializer.flush();
19727        } catch (Exception e) {
19728            if (DEBUG_BACKUP) {
19729                Slog.e(TAG, "Unable to write default apps for backup", e);
19730            }
19731            return null;
19732        }
19733
19734        return dataStream.toByteArray();
19735    }
19736
19737    @Override
19738    public void restoreDefaultApps(byte[] backup, int userId) {
19739        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19740            throw new SecurityException("Only the system may call restoreDefaultApps()");
19741        }
19742
19743        try {
19744            final XmlPullParser parser = Xml.newPullParser();
19745            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19746            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19747                    new BlobXmlRestorer() {
19748                        @Override
19749                        public void apply(XmlPullParser parser, int userId)
19750                                throws XmlPullParserException, IOException {
19751                            synchronized (mPackages) {
19752                                mSettings.readDefaultAppsLPw(parser, userId);
19753                            }
19754                        }
19755                    } );
19756        } catch (Exception e) {
19757            if (DEBUG_BACKUP) {
19758                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19759            }
19760        }
19761    }
19762
19763    @Override
19764    public byte[] getIntentFilterVerificationBackup(int userId) {
19765        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19766            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19767        }
19768
19769        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19770        try {
19771            final XmlSerializer serializer = new FastXmlSerializer();
19772            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19773            serializer.startDocument(null, true);
19774            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19775
19776            synchronized (mPackages) {
19777                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19778            }
19779
19780            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19781            serializer.endDocument();
19782            serializer.flush();
19783        } catch (Exception e) {
19784            if (DEBUG_BACKUP) {
19785                Slog.e(TAG, "Unable to write default apps for backup", e);
19786            }
19787            return null;
19788        }
19789
19790        return dataStream.toByteArray();
19791    }
19792
19793    @Override
19794    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19795        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19796            throw new SecurityException("Only the system may call restorePreferredActivities()");
19797        }
19798
19799        try {
19800            final XmlPullParser parser = Xml.newPullParser();
19801            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19802            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19803                    new BlobXmlRestorer() {
19804                        @Override
19805                        public void apply(XmlPullParser parser, int userId)
19806                                throws XmlPullParserException, IOException {
19807                            synchronized (mPackages) {
19808                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19809                                mSettings.writeLPr();
19810                            }
19811                        }
19812                    } );
19813        } catch (Exception e) {
19814            if (DEBUG_BACKUP) {
19815                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19816            }
19817        }
19818    }
19819
19820    @Override
19821    public byte[] getPermissionGrantBackup(int userId) {
19822        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19823            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19824        }
19825
19826        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19827        try {
19828            final XmlSerializer serializer = new FastXmlSerializer();
19829            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19830            serializer.startDocument(null, true);
19831            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19832
19833            synchronized (mPackages) {
19834                serializeRuntimePermissionGrantsLPr(serializer, userId);
19835            }
19836
19837            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19838            serializer.endDocument();
19839            serializer.flush();
19840        } catch (Exception e) {
19841            if (DEBUG_BACKUP) {
19842                Slog.e(TAG, "Unable to write default apps for backup", e);
19843            }
19844            return null;
19845        }
19846
19847        return dataStream.toByteArray();
19848    }
19849
19850    @Override
19851    public void restorePermissionGrants(byte[] backup, int userId) {
19852        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19853            throw new SecurityException("Only the system may call restorePermissionGrants()");
19854        }
19855
19856        try {
19857            final XmlPullParser parser = Xml.newPullParser();
19858            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19859            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19860                    new BlobXmlRestorer() {
19861                        @Override
19862                        public void apply(XmlPullParser parser, int userId)
19863                                throws XmlPullParserException, IOException {
19864                            synchronized (mPackages) {
19865                                processRestoredPermissionGrantsLPr(parser, userId);
19866                            }
19867                        }
19868                    } );
19869        } catch (Exception e) {
19870            if (DEBUG_BACKUP) {
19871                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19872            }
19873        }
19874    }
19875
19876    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19877            throws IOException {
19878        serializer.startTag(null, TAG_ALL_GRANTS);
19879
19880        final int N = mSettings.mPackages.size();
19881        for (int i = 0; i < N; i++) {
19882            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19883            boolean pkgGrantsKnown = false;
19884
19885            PermissionsState packagePerms = ps.getPermissionsState();
19886
19887            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19888                final int grantFlags = state.getFlags();
19889                // only look at grants that are not system/policy fixed
19890                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19891                    final boolean isGranted = state.isGranted();
19892                    // And only back up the user-twiddled state bits
19893                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19894                        final String packageName = mSettings.mPackages.keyAt(i);
19895                        if (!pkgGrantsKnown) {
19896                            serializer.startTag(null, TAG_GRANT);
19897                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19898                            pkgGrantsKnown = true;
19899                        }
19900
19901                        final boolean userSet =
19902                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19903                        final boolean userFixed =
19904                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19905                        final boolean revoke =
19906                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19907
19908                        serializer.startTag(null, TAG_PERMISSION);
19909                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19910                        if (isGranted) {
19911                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19912                        }
19913                        if (userSet) {
19914                            serializer.attribute(null, ATTR_USER_SET, "true");
19915                        }
19916                        if (userFixed) {
19917                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19918                        }
19919                        if (revoke) {
19920                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19921                        }
19922                        serializer.endTag(null, TAG_PERMISSION);
19923                    }
19924                }
19925            }
19926
19927            if (pkgGrantsKnown) {
19928                serializer.endTag(null, TAG_GRANT);
19929            }
19930        }
19931
19932        serializer.endTag(null, TAG_ALL_GRANTS);
19933    }
19934
19935    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19936            throws XmlPullParserException, IOException {
19937        String pkgName = null;
19938        int outerDepth = parser.getDepth();
19939        int type;
19940        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19941                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19942            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19943                continue;
19944            }
19945
19946            final String tagName = parser.getName();
19947            if (tagName.equals(TAG_GRANT)) {
19948                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19949                if (DEBUG_BACKUP) {
19950                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19951                }
19952            } else if (tagName.equals(TAG_PERMISSION)) {
19953
19954                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19955                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19956
19957                int newFlagSet = 0;
19958                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19959                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19960                }
19961                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19962                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19963                }
19964                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19965                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19966                }
19967                if (DEBUG_BACKUP) {
19968                    Slog.v(TAG, "  + Restoring grant:"
19969                            + " pkg=" + pkgName
19970                            + " perm=" + permName
19971                            + " granted=" + isGranted
19972                            + " bits=0x" + Integer.toHexString(newFlagSet));
19973                }
19974                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19975                if (ps != null) {
19976                    // Already installed so we apply the grant immediately
19977                    if (DEBUG_BACKUP) {
19978                        Slog.v(TAG, "        + already installed; applying");
19979                    }
19980                    PermissionsState perms = ps.getPermissionsState();
19981                    BasePermission bp =
19982                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19983                    if (bp != null) {
19984                        if (isGranted) {
19985                            perms.grantRuntimePermission(bp, userId);
19986                        }
19987                        if (newFlagSet != 0) {
19988                            perms.updatePermissionFlags(
19989                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19990                        }
19991                    }
19992                } else {
19993                    // Need to wait for post-restore install to apply the grant
19994                    if (DEBUG_BACKUP) {
19995                        Slog.v(TAG, "        - not yet installed; saving for later");
19996                    }
19997                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19998                            isGranted, newFlagSet, userId);
19999                }
20000            } else {
20001                PackageManagerService.reportSettingsProblem(Log.WARN,
20002                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20003                XmlUtils.skipCurrentTag(parser);
20004            }
20005        }
20006
20007        scheduleWriteSettingsLocked();
20008        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20009    }
20010
20011    @Override
20012    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20013            int sourceUserId, int targetUserId, int flags) {
20014        mContext.enforceCallingOrSelfPermission(
20015                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20016        int callingUid = Binder.getCallingUid();
20017        enforceOwnerRights(ownerPackage, callingUid);
20018        PackageManagerServiceUtils.enforceShellRestriction(
20019                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20020        if (intentFilter.countActions() == 0) {
20021            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20022            return;
20023        }
20024        synchronized (mPackages) {
20025            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20026                    ownerPackage, targetUserId, flags);
20027            CrossProfileIntentResolver resolver =
20028                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20029            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20030            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20031            if (existing != null) {
20032                int size = existing.size();
20033                for (int i = 0; i < size; i++) {
20034                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20035                        return;
20036                    }
20037                }
20038            }
20039            resolver.addFilter(newFilter);
20040            scheduleWritePackageRestrictionsLocked(sourceUserId);
20041        }
20042    }
20043
20044    @Override
20045    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20046        mContext.enforceCallingOrSelfPermission(
20047                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20048        final int callingUid = Binder.getCallingUid();
20049        enforceOwnerRights(ownerPackage, callingUid);
20050        PackageManagerServiceUtils.enforceShellRestriction(
20051                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20052        synchronized (mPackages) {
20053            CrossProfileIntentResolver resolver =
20054                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20055            ArraySet<CrossProfileIntentFilter> set =
20056                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20057            for (CrossProfileIntentFilter filter : set) {
20058                if (filter.getOwnerPackage().equals(ownerPackage)) {
20059                    resolver.removeFilter(filter);
20060                }
20061            }
20062            scheduleWritePackageRestrictionsLocked(sourceUserId);
20063        }
20064    }
20065
20066    // Enforcing that callingUid is owning pkg on userId
20067    private void enforceOwnerRights(String pkg, int callingUid) {
20068        // The system owns everything.
20069        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20070            return;
20071        }
20072        final int callingUserId = UserHandle.getUserId(callingUid);
20073        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20074        if (pi == null) {
20075            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20076                    + callingUserId);
20077        }
20078        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20079            throw new SecurityException("Calling uid " + callingUid
20080                    + " does not own package " + pkg);
20081        }
20082    }
20083
20084    @Override
20085    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20086        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20087            return null;
20088        }
20089        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20090    }
20091
20092    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20093        UserManagerService ums = UserManagerService.getInstance();
20094        if (ums != null) {
20095            final UserInfo parent = ums.getProfileParent(userId);
20096            final int launcherUid = (parent != null) ? parent.id : userId;
20097            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20098            if (launcherComponent != null) {
20099                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20100                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20101                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20102                        .setPackage(launcherComponent.getPackageName());
20103                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20104            }
20105        }
20106    }
20107
20108    /**
20109     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20110     * then reports the most likely home activity or null if there are more than one.
20111     */
20112    private ComponentName getDefaultHomeActivity(int userId) {
20113        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20114        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20115        if (cn != null) {
20116            return cn;
20117        }
20118
20119        // Find the launcher with the highest priority and return that component if there are no
20120        // other home activity with the same priority.
20121        int lastPriority = Integer.MIN_VALUE;
20122        ComponentName lastComponent = null;
20123        final int size = allHomeCandidates.size();
20124        for (int i = 0; i < size; i++) {
20125            final ResolveInfo ri = allHomeCandidates.get(i);
20126            if (ri.priority > lastPriority) {
20127                lastComponent = ri.activityInfo.getComponentName();
20128                lastPriority = ri.priority;
20129            } else if (ri.priority == lastPriority) {
20130                // Two components found with same priority.
20131                lastComponent = null;
20132            }
20133        }
20134        return lastComponent;
20135    }
20136
20137    private Intent getHomeIntent() {
20138        Intent intent = new Intent(Intent.ACTION_MAIN);
20139        intent.addCategory(Intent.CATEGORY_HOME);
20140        intent.addCategory(Intent.CATEGORY_DEFAULT);
20141        return intent;
20142    }
20143
20144    private IntentFilter getHomeFilter() {
20145        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20146        filter.addCategory(Intent.CATEGORY_HOME);
20147        filter.addCategory(Intent.CATEGORY_DEFAULT);
20148        return filter;
20149    }
20150
20151    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20152            int userId) {
20153        Intent intent  = getHomeIntent();
20154        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20155                PackageManager.GET_META_DATA, userId);
20156        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20157                true, false, false, userId);
20158
20159        allHomeCandidates.clear();
20160        if (list != null) {
20161            for (ResolveInfo ri : list) {
20162                allHomeCandidates.add(ri);
20163            }
20164        }
20165        return (preferred == null || preferred.activityInfo == null)
20166                ? null
20167                : new ComponentName(preferred.activityInfo.packageName,
20168                        preferred.activityInfo.name);
20169    }
20170
20171    @Override
20172    public void setHomeActivity(ComponentName comp, int userId) {
20173        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20174            return;
20175        }
20176        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20177        getHomeActivitiesAsUser(homeActivities, userId);
20178
20179        boolean found = false;
20180
20181        final int size = homeActivities.size();
20182        final ComponentName[] set = new ComponentName[size];
20183        for (int i = 0; i < size; i++) {
20184            final ResolveInfo candidate = homeActivities.get(i);
20185            final ActivityInfo info = candidate.activityInfo;
20186            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20187            set[i] = activityName;
20188            if (!found && activityName.equals(comp)) {
20189                found = true;
20190            }
20191        }
20192        if (!found) {
20193            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20194                    + userId);
20195        }
20196        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20197                set, comp, userId);
20198    }
20199
20200    private @Nullable String getSetupWizardPackageName() {
20201        final Intent intent = new Intent(Intent.ACTION_MAIN);
20202        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20203
20204        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20205                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20206                        | MATCH_DISABLED_COMPONENTS,
20207                UserHandle.myUserId());
20208        if (matches.size() == 1) {
20209            return matches.get(0).getComponentInfo().packageName;
20210        } else {
20211            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20212                    + ": matches=" + matches);
20213            return null;
20214        }
20215    }
20216
20217    private @Nullable String getStorageManagerPackageName() {
20218        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20219
20220        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20221                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20222                        | MATCH_DISABLED_COMPONENTS,
20223                UserHandle.myUserId());
20224        if (matches.size() == 1) {
20225            return matches.get(0).getComponentInfo().packageName;
20226        } else {
20227            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20228                    + matches.size() + ": matches=" + matches);
20229            return null;
20230        }
20231    }
20232
20233    @Override
20234    public void setApplicationEnabledSetting(String appPackageName,
20235            int newState, int flags, int userId, String callingPackage) {
20236        if (!sUserManager.exists(userId)) return;
20237        if (callingPackage == null) {
20238            callingPackage = Integer.toString(Binder.getCallingUid());
20239        }
20240        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20241    }
20242
20243    @Override
20244    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20245        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20246        synchronized (mPackages) {
20247            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20248            if (pkgSetting != null) {
20249                pkgSetting.setUpdateAvailable(updateAvailable);
20250            }
20251        }
20252    }
20253
20254    @Override
20255    public void setComponentEnabledSetting(ComponentName componentName,
20256            int newState, int flags, int userId) {
20257        if (!sUserManager.exists(userId)) return;
20258        setEnabledSetting(componentName.getPackageName(),
20259                componentName.getClassName(), newState, flags, userId, null);
20260    }
20261
20262    private void setEnabledSetting(final String packageName, String className, int newState,
20263            final int flags, int userId, String callingPackage) {
20264        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20265              || newState == COMPONENT_ENABLED_STATE_ENABLED
20266              || newState == COMPONENT_ENABLED_STATE_DISABLED
20267              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20268              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20269            throw new IllegalArgumentException("Invalid new component state: "
20270                    + newState);
20271        }
20272        PackageSetting pkgSetting;
20273        final int callingUid = Binder.getCallingUid();
20274        final int permission;
20275        if (callingUid == Process.SYSTEM_UID) {
20276            permission = PackageManager.PERMISSION_GRANTED;
20277        } else {
20278            permission = mContext.checkCallingOrSelfPermission(
20279                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20280        }
20281        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20282                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20283        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20284        boolean sendNow = false;
20285        boolean isApp = (className == null);
20286        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20287        String componentName = isApp ? packageName : className;
20288        int packageUid = -1;
20289        ArrayList<String> components;
20290
20291        // reader
20292        synchronized (mPackages) {
20293            pkgSetting = mSettings.mPackages.get(packageName);
20294            if (pkgSetting == null) {
20295                if (!isCallerInstantApp) {
20296                    if (className == null) {
20297                        throw new IllegalArgumentException("Unknown package: " + packageName);
20298                    }
20299                    throw new IllegalArgumentException(
20300                            "Unknown component: " + packageName + "/" + className);
20301                } else {
20302                    // throw SecurityException to prevent leaking package information
20303                    throw new SecurityException(
20304                            "Attempt to change component state; "
20305                            + "pid=" + Binder.getCallingPid()
20306                            + ", uid=" + callingUid
20307                            + (className == null
20308                                    ? ", package=" + packageName
20309                                    : ", component=" + packageName + "/" + className));
20310                }
20311            }
20312        }
20313
20314        // Limit who can change which apps
20315        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20316            // Don't allow apps that don't have permission to modify other apps
20317            if (!allowedByPermission
20318                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20319                throw new SecurityException(
20320                        "Attempt to change component state; "
20321                        + "pid=" + Binder.getCallingPid()
20322                        + ", uid=" + callingUid
20323                        + (className == null
20324                                ? ", package=" + packageName
20325                                : ", component=" + packageName + "/" + className));
20326            }
20327            // Don't allow changing protected packages.
20328            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20329                throw new SecurityException("Cannot disable a protected package: " + packageName);
20330            }
20331        }
20332
20333        synchronized (mPackages) {
20334            if (callingUid == Process.SHELL_UID
20335                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20336                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20337                // unless it is a test package.
20338                int oldState = pkgSetting.getEnabled(userId);
20339                if (className == null
20340                        &&
20341                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20342                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20343                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20344                        &&
20345                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20346                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20347                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20348                    // ok
20349                } else {
20350                    throw new SecurityException(
20351                            "Shell cannot change component state for " + packageName + "/"
20352                                    + className + " to " + newState);
20353                }
20354            }
20355        }
20356        if (className == null) {
20357            // We're dealing with an application/package level state change
20358            synchronized (mPackages) {
20359                if (pkgSetting.getEnabled(userId) == newState) {
20360                    // Nothing to do
20361                    return;
20362                }
20363            }
20364            // If we're enabling a system stub, there's a little more work to do.
20365            // Prior to enabling the package, we need to decompress the APK(s) to the
20366            // data partition and then replace the version on the system partition.
20367            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20368            final boolean isSystemStub = deletedPkg.isStub
20369                    && deletedPkg.isSystem();
20370            if (isSystemStub
20371                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20372                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20373                final File codePath = decompressPackage(deletedPkg);
20374                if (codePath == null) {
20375                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20376                    return;
20377                }
20378                // TODO remove direct parsing of the package object during internal cleanup
20379                // of scan package
20380                // We need to call parse directly here for no other reason than we need
20381                // the new package in order to disable the old one [we use the information
20382                // for some internal optimization to optionally create a new package setting
20383                // object on replace]. However, we can't get the package from the scan
20384                // because the scan modifies live structures and we need to remove the
20385                // old [system] package from the system before a scan can be attempted.
20386                // Once scan is indempotent we can remove this parse and use the package
20387                // object we scanned, prior to adding it to package settings.
20388                final PackageParser pp = new PackageParser();
20389                pp.setSeparateProcesses(mSeparateProcesses);
20390                pp.setDisplayMetrics(mMetrics);
20391                pp.setCallback(mPackageParserCallback);
20392                final PackageParser.Package tmpPkg;
20393                try {
20394                    final @ParseFlags int parseFlags = mDefParseFlags
20395                            | PackageParser.PARSE_MUST_BE_APK
20396                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20397                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20398                } catch (PackageParserException e) {
20399                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20400                    return;
20401                }
20402                synchronized (mInstallLock) {
20403                    // Disable the stub and remove any package entries
20404                    removePackageLI(deletedPkg, true);
20405                    synchronized (mPackages) {
20406                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20407                    }
20408                    final PackageParser.Package pkg;
20409                    try (PackageFreezer freezer =
20410                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20411                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20412                                | PackageParser.PARSE_ENFORCE_CODE;
20413                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20414                                0 /*currentTime*/, null /*user*/);
20415                        prepareAppDataAfterInstallLIF(pkg);
20416                        synchronized (mPackages) {
20417                            try {
20418                                updateSharedLibrariesLPr(pkg, null);
20419                            } catch (PackageManagerException e) {
20420                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20421                            }
20422                            mPermissionManager.updatePermissions(
20423                                    pkg.packageName, pkg, true, mPackages.values(),
20424                                    mPermissionCallback);
20425                            mSettings.writeLPr();
20426                        }
20427                    } catch (PackageManagerException e) {
20428                        // Whoops! Something went wrong; try to roll back to the stub
20429                        Slog.w(TAG, "Failed to install compressed system package:"
20430                                + pkgSetting.name, e);
20431                        // Remove the failed install
20432                        removeCodePathLI(codePath);
20433
20434                        // Install the system package
20435                        try (PackageFreezer freezer =
20436                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20437                            synchronized (mPackages) {
20438                                // NOTE: The system package always needs to be enabled; even
20439                                // if it's for a compressed stub. If we don't, installing the
20440                                // system package fails during scan [scanning checks the disabled
20441                                // packages]. We will reverse this later, after we've "installed"
20442                                // the stub.
20443                                // This leaves us in a fragile state; the stub should never be
20444                                // enabled, so, cross your fingers and hope nothing goes wrong
20445                                // until we can disable the package later.
20446                                enableSystemPackageLPw(deletedPkg);
20447                            }
20448                            installPackageFromSystemLIF(deletedPkg.codePath,
20449                                    false /*isPrivileged*/, null /*allUserHandles*/,
20450                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20451                                    true /*writeSettings*/);
20452                        } catch (PackageManagerException pme) {
20453                            Slog.w(TAG, "Failed to restore system package:"
20454                                    + deletedPkg.packageName, pme);
20455                        } finally {
20456                            synchronized (mPackages) {
20457                                mSettings.disableSystemPackageLPw(
20458                                        deletedPkg.packageName, true /*replaced*/);
20459                                mSettings.writeLPr();
20460                            }
20461                        }
20462                        return;
20463                    }
20464                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20465                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20466                    mDexManager.notifyPackageUpdated(pkg.packageName,
20467                            pkg.baseCodePath, pkg.splitCodePaths);
20468                }
20469            }
20470            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20471                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20472                // Don't care about who enables an app.
20473                callingPackage = null;
20474            }
20475            synchronized (mPackages) {
20476                pkgSetting.setEnabled(newState, userId, callingPackage);
20477            }
20478        } else {
20479            synchronized (mPackages) {
20480                // We're dealing with a component level state change
20481                // First, verify that this is a valid class name.
20482                PackageParser.Package pkg = pkgSetting.pkg;
20483                if (pkg == null || !pkg.hasComponentClassName(className)) {
20484                    if (pkg != null &&
20485                            pkg.applicationInfo.targetSdkVersion >=
20486                                    Build.VERSION_CODES.JELLY_BEAN) {
20487                        throw new IllegalArgumentException("Component class " + className
20488                                + " does not exist in " + packageName);
20489                    } else {
20490                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20491                                + className + " does not exist in " + packageName);
20492                    }
20493                }
20494                switch (newState) {
20495                    case COMPONENT_ENABLED_STATE_ENABLED:
20496                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20497                            return;
20498                        }
20499                        break;
20500                    case COMPONENT_ENABLED_STATE_DISABLED:
20501                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20502                            return;
20503                        }
20504                        break;
20505                    case COMPONENT_ENABLED_STATE_DEFAULT:
20506                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20507                            return;
20508                        }
20509                        break;
20510                    default:
20511                        Slog.e(TAG, "Invalid new component state: " + newState);
20512                        return;
20513                }
20514            }
20515        }
20516        synchronized (mPackages) {
20517            scheduleWritePackageRestrictionsLocked(userId);
20518            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20519            final long callingId = Binder.clearCallingIdentity();
20520            try {
20521                updateInstantAppInstallerLocked(packageName);
20522            } finally {
20523                Binder.restoreCallingIdentity(callingId);
20524            }
20525            components = mPendingBroadcasts.get(userId, packageName);
20526            final boolean newPackage = components == null;
20527            if (newPackage) {
20528                components = new ArrayList<String>();
20529            }
20530            if (!components.contains(componentName)) {
20531                components.add(componentName);
20532            }
20533            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20534                sendNow = true;
20535                // Purge entry from pending broadcast list if another one exists already
20536                // since we are sending one right away.
20537                mPendingBroadcasts.remove(userId, packageName);
20538            } else {
20539                if (newPackage) {
20540                    mPendingBroadcasts.put(userId, packageName, components);
20541                }
20542                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20543                    // Schedule a message
20544                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20545                }
20546            }
20547        }
20548
20549        long callingId = Binder.clearCallingIdentity();
20550        try {
20551            if (sendNow) {
20552                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20553                sendPackageChangedBroadcast(packageName,
20554                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20555            }
20556        } finally {
20557            Binder.restoreCallingIdentity(callingId);
20558        }
20559    }
20560
20561    @Override
20562    public void flushPackageRestrictionsAsUser(int userId) {
20563        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20564            return;
20565        }
20566        if (!sUserManager.exists(userId)) {
20567            return;
20568        }
20569        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20570                false /* checkShell */, "flushPackageRestrictions");
20571        synchronized (mPackages) {
20572            mSettings.writePackageRestrictionsLPr(userId);
20573            mDirtyUsers.remove(userId);
20574            if (mDirtyUsers.isEmpty()) {
20575                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20576            }
20577        }
20578    }
20579
20580    private void sendPackageChangedBroadcast(String packageName,
20581            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20582        if (DEBUG_INSTALL)
20583            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20584                    + componentNames);
20585        Bundle extras = new Bundle(4);
20586        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20587        String nameList[] = new String[componentNames.size()];
20588        componentNames.toArray(nameList);
20589        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20590        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20591        extras.putInt(Intent.EXTRA_UID, packageUid);
20592        // If this is not reporting a change of the overall package, then only send it
20593        // to registered receivers.  We don't want to launch a swath of apps for every
20594        // little component state change.
20595        final int flags = !componentNames.contains(packageName)
20596                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20597        final int userId = UserHandle.getUserId(packageUid);
20598        final boolean isInstantApp = isInstantApp(packageName, userId);
20599        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20600        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20601        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20602                userIds, instantUserIds);
20603    }
20604
20605    @Override
20606    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20607        if (!sUserManager.exists(userId)) return;
20608        final int callingUid = Binder.getCallingUid();
20609        if (getInstantAppPackageName(callingUid) != null) {
20610            return;
20611        }
20612        final int permission = mContext.checkCallingOrSelfPermission(
20613                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20614        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20615        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20616                true /* requireFullPermission */, true /* checkShell */, "stop package");
20617        // writer
20618        synchronized (mPackages) {
20619            final PackageSetting ps = mSettings.mPackages.get(packageName);
20620            if (!filterAppAccessLPr(ps, callingUid, userId)
20621                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20622                            allowedByPermission, callingUid, userId)) {
20623                scheduleWritePackageRestrictionsLocked(userId);
20624            }
20625        }
20626    }
20627
20628    @Override
20629    public String getInstallerPackageName(String packageName) {
20630        final int callingUid = Binder.getCallingUid();
20631        if (getInstantAppPackageName(callingUid) != null) {
20632            return null;
20633        }
20634        // reader
20635        synchronized (mPackages) {
20636            final PackageSetting ps = mSettings.mPackages.get(packageName);
20637            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20638                return null;
20639            }
20640            return mSettings.getInstallerPackageNameLPr(packageName);
20641        }
20642    }
20643
20644    public boolean isOrphaned(String packageName) {
20645        // reader
20646        synchronized (mPackages) {
20647            return mSettings.isOrphaned(packageName);
20648        }
20649    }
20650
20651    @Override
20652    public int getApplicationEnabledSetting(String packageName, int userId) {
20653        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20654        int callingUid = Binder.getCallingUid();
20655        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20656                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20657        // reader
20658        synchronized (mPackages) {
20659            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20660                return COMPONENT_ENABLED_STATE_DISABLED;
20661            }
20662            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20663        }
20664    }
20665
20666    @Override
20667    public int getComponentEnabledSetting(ComponentName component, int userId) {
20668        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20669        int callingUid = Binder.getCallingUid();
20670        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20671                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20672        synchronized (mPackages) {
20673            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20674                    component, TYPE_UNKNOWN, userId)) {
20675                return COMPONENT_ENABLED_STATE_DISABLED;
20676            }
20677            return mSettings.getComponentEnabledSettingLPr(component, userId);
20678        }
20679    }
20680
20681    @Override
20682    public void enterSafeMode() {
20683        enforceSystemOrRoot("Only the system can request entering safe mode");
20684
20685        if (!mSystemReady) {
20686            mSafeMode = true;
20687        }
20688    }
20689
20690    @Override
20691    public void systemReady() {
20692        enforceSystemOrRoot("Only the system can claim the system is ready");
20693
20694        mSystemReady = true;
20695        final ContentResolver resolver = mContext.getContentResolver();
20696        ContentObserver co = new ContentObserver(mHandler) {
20697            @Override
20698            public void onChange(boolean selfChange) {
20699                mEphemeralAppsDisabled =
20700                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20701                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20702            }
20703        };
20704        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20705                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20706                false, co, UserHandle.USER_SYSTEM);
20707        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20708                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20709        co.onChange(true);
20710
20711        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20712        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20713        // it is done.
20714        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20715            @Override
20716            public void onChange(boolean selfChange) {
20717                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20718                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20719                        oobEnabled == 1 ? "true" : "false");
20720            }
20721        };
20722        mContext.getContentResolver().registerContentObserver(
20723                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20724                UserHandle.USER_SYSTEM);
20725        // At boot, restore the value from the setting, which persists across reboot.
20726        privAppOobObserver.onChange(true);
20727
20728        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20729        // disabled after already being started.
20730        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20731                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20732
20733        // Read the compatibilty setting when the system is ready.
20734        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20735                mContext.getContentResolver(),
20736                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20737        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20738        if (DEBUG_SETTINGS) {
20739            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20740        }
20741
20742        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20743
20744        synchronized (mPackages) {
20745            // Verify that all of the preferred activity components actually
20746            // exist.  It is possible for applications to be updated and at
20747            // that point remove a previously declared activity component that
20748            // had been set as a preferred activity.  We try to clean this up
20749            // the next time we encounter that preferred activity, but it is
20750            // possible for the user flow to never be able to return to that
20751            // situation so here we do a sanity check to make sure we haven't
20752            // left any junk around.
20753            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20754            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20755                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20756                removed.clear();
20757                for (PreferredActivity pa : pir.filterSet()) {
20758                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20759                        removed.add(pa);
20760                    }
20761                }
20762                if (removed.size() > 0) {
20763                    for (int r=0; r<removed.size(); r++) {
20764                        PreferredActivity pa = removed.get(r);
20765                        Slog.w(TAG, "Removing dangling preferred activity: "
20766                                + pa.mPref.mComponent);
20767                        pir.removeFilter(pa);
20768                    }
20769                    mSettings.writePackageRestrictionsLPr(
20770                            mSettings.mPreferredActivities.keyAt(i));
20771                }
20772            }
20773
20774            for (int userId : UserManagerService.getInstance().getUserIds()) {
20775                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20776                    grantPermissionsUserIds = ArrayUtils.appendInt(
20777                            grantPermissionsUserIds, userId);
20778                }
20779            }
20780        }
20781        sUserManager.systemReady();
20782        // If we upgraded grant all default permissions before kicking off.
20783        for (int userId : grantPermissionsUserIds) {
20784            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20785        }
20786
20787        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20788            // If we did not grant default permissions, we preload from this the
20789            // default permission exceptions lazily to ensure we don't hit the
20790            // disk on a new user creation.
20791            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20792        }
20793
20794        // Now that we've scanned all packages, and granted any default
20795        // permissions, ensure permissions are updated. Beware of dragons if you
20796        // try optimizing this.
20797        synchronized (mPackages) {
20798            mPermissionManager.updateAllPermissions(
20799                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20800                    mPermissionCallback);
20801        }
20802
20803        // Kick off any messages waiting for system ready
20804        if (mPostSystemReadyMessages != null) {
20805            for (Message msg : mPostSystemReadyMessages) {
20806                msg.sendToTarget();
20807            }
20808            mPostSystemReadyMessages = null;
20809        }
20810
20811        // Watch for external volumes that come and go over time
20812        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20813        storage.registerListener(mStorageListener);
20814
20815        mInstallerService.systemReady();
20816        mPackageDexOptimizer.systemReady();
20817
20818        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20819                StorageManagerInternal.class);
20820        StorageManagerInternal.addExternalStoragePolicy(
20821                new StorageManagerInternal.ExternalStorageMountPolicy() {
20822            @Override
20823            public int getMountMode(int uid, String packageName) {
20824                if (Process.isIsolated(uid)) {
20825                    return Zygote.MOUNT_EXTERNAL_NONE;
20826                }
20827                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20828                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20829                }
20830                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20831                    return Zygote.MOUNT_EXTERNAL_READ;
20832                }
20833                return Zygote.MOUNT_EXTERNAL_WRITE;
20834            }
20835
20836            @Override
20837            public boolean hasExternalStorage(int uid, String packageName) {
20838                return true;
20839            }
20840        });
20841
20842        // Now that we're mostly running, clean up stale users and apps
20843        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20844        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20845
20846        mPermissionManager.systemReady();
20847    }
20848
20849    public void waitForAppDataPrepared() {
20850        if (mPrepareAppDataFuture == null) {
20851            return;
20852        }
20853        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20854        mPrepareAppDataFuture = null;
20855    }
20856
20857    @Override
20858    public boolean isSafeMode() {
20859        // allow instant applications
20860        return mSafeMode;
20861    }
20862
20863    @Override
20864    public boolean hasSystemUidErrors() {
20865        // allow instant applications
20866        return mHasSystemUidErrors;
20867    }
20868
20869    static String arrayToString(int[] array) {
20870        StringBuffer buf = new StringBuffer(128);
20871        buf.append('[');
20872        if (array != null) {
20873            for (int i=0; i<array.length; i++) {
20874                if (i > 0) buf.append(", ");
20875                buf.append(array[i]);
20876            }
20877        }
20878        buf.append(']');
20879        return buf.toString();
20880    }
20881
20882    @Override
20883    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20884            FileDescriptor err, String[] args, ShellCallback callback,
20885            ResultReceiver resultReceiver) {
20886        (new PackageManagerShellCommand(this)).exec(
20887                this, in, out, err, args, callback, resultReceiver);
20888    }
20889
20890    @Override
20891    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20892        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20893
20894        DumpState dumpState = new DumpState();
20895        boolean fullPreferred = false;
20896        boolean checkin = false;
20897
20898        String packageName = null;
20899        ArraySet<String> permissionNames = null;
20900
20901        int opti = 0;
20902        while (opti < args.length) {
20903            String opt = args[opti];
20904            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20905                break;
20906            }
20907            opti++;
20908
20909            if ("-a".equals(opt)) {
20910                // Right now we only know how to print all.
20911            } else if ("-h".equals(opt)) {
20912                pw.println("Package manager dump options:");
20913                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20914                pw.println("    --checkin: dump for a checkin");
20915                pw.println("    -f: print details of intent filters");
20916                pw.println("    -h: print this help");
20917                pw.println("  cmd may be one of:");
20918                pw.println("    l[ibraries]: list known shared libraries");
20919                pw.println("    f[eatures]: list device features");
20920                pw.println("    k[eysets]: print known keysets");
20921                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20922                pw.println("    perm[issions]: dump permissions");
20923                pw.println("    permission [name ...]: dump declaration and use of given permission");
20924                pw.println("    pref[erred]: print preferred package settings");
20925                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20926                pw.println("    prov[iders]: dump content providers");
20927                pw.println("    p[ackages]: dump installed packages");
20928                pw.println("    s[hared-users]: dump shared user IDs");
20929                pw.println("    m[essages]: print collected runtime messages");
20930                pw.println("    v[erifiers]: print package verifier info");
20931                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20932                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20933                pw.println("    version: print database version info");
20934                pw.println("    write: write current settings now");
20935                pw.println("    installs: details about install sessions");
20936                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20937                pw.println("    dexopt: dump dexopt state");
20938                pw.println("    compiler-stats: dump compiler statistics");
20939                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20940                pw.println("    service-permissions: dump permissions required by services");
20941                pw.println("    <package.name>: info about given package");
20942                return;
20943            } else if ("--checkin".equals(opt)) {
20944                checkin = true;
20945            } else if ("-f".equals(opt)) {
20946                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20947            } else if ("--proto".equals(opt)) {
20948                dumpProto(fd);
20949                return;
20950            } else {
20951                pw.println("Unknown argument: " + opt + "; use -h for help");
20952            }
20953        }
20954
20955        // Is the caller requesting to dump a particular piece of data?
20956        if (opti < args.length) {
20957            String cmd = args[opti];
20958            opti++;
20959            // Is this a package name?
20960            if ("android".equals(cmd) || cmd.contains(".")) {
20961                packageName = cmd;
20962                // When dumping a single package, we always dump all of its
20963                // filter information since the amount of data will be reasonable.
20964                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20965            } else if ("check-permission".equals(cmd)) {
20966                if (opti >= args.length) {
20967                    pw.println("Error: check-permission missing permission argument");
20968                    return;
20969                }
20970                String perm = args[opti];
20971                opti++;
20972                if (opti >= args.length) {
20973                    pw.println("Error: check-permission missing package argument");
20974                    return;
20975                }
20976
20977                String pkg = args[opti];
20978                opti++;
20979                int user = UserHandle.getUserId(Binder.getCallingUid());
20980                if (opti < args.length) {
20981                    try {
20982                        user = Integer.parseInt(args[opti]);
20983                    } catch (NumberFormatException e) {
20984                        pw.println("Error: check-permission user argument is not a number: "
20985                                + args[opti]);
20986                        return;
20987                    }
20988                }
20989
20990                // Normalize package name to handle renamed packages and static libs
20991                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20992
20993                pw.println(checkPermission(perm, pkg, user));
20994                return;
20995            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20996                dumpState.setDump(DumpState.DUMP_LIBS);
20997            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20998                dumpState.setDump(DumpState.DUMP_FEATURES);
20999            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21000                if (opti >= args.length) {
21001                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21002                            | DumpState.DUMP_SERVICE_RESOLVERS
21003                            | DumpState.DUMP_RECEIVER_RESOLVERS
21004                            | DumpState.DUMP_CONTENT_RESOLVERS);
21005                } else {
21006                    while (opti < args.length) {
21007                        String name = args[opti];
21008                        if ("a".equals(name) || "activity".equals(name)) {
21009                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21010                        } else if ("s".equals(name) || "service".equals(name)) {
21011                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21012                        } else if ("r".equals(name) || "receiver".equals(name)) {
21013                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21014                        } else if ("c".equals(name) || "content".equals(name)) {
21015                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21016                        } else {
21017                            pw.println("Error: unknown resolver table type: " + name);
21018                            return;
21019                        }
21020                        opti++;
21021                    }
21022                }
21023            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21024                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21025            } else if ("permission".equals(cmd)) {
21026                if (opti >= args.length) {
21027                    pw.println("Error: permission requires permission name");
21028                    return;
21029                }
21030                permissionNames = new ArraySet<>();
21031                while (opti < args.length) {
21032                    permissionNames.add(args[opti]);
21033                    opti++;
21034                }
21035                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21036                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21037            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21038                dumpState.setDump(DumpState.DUMP_PREFERRED);
21039            } else if ("preferred-xml".equals(cmd)) {
21040                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21041                if (opti < args.length && "--full".equals(args[opti])) {
21042                    fullPreferred = true;
21043                    opti++;
21044                }
21045            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21046                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21047            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21048                dumpState.setDump(DumpState.DUMP_PACKAGES);
21049            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21050                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21051            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21052                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21053            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21054                dumpState.setDump(DumpState.DUMP_MESSAGES);
21055            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21056                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21057            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21058                    || "intent-filter-verifiers".equals(cmd)) {
21059                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21060            } else if ("version".equals(cmd)) {
21061                dumpState.setDump(DumpState.DUMP_VERSION);
21062            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21063                dumpState.setDump(DumpState.DUMP_KEYSETS);
21064            } else if ("installs".equals(cmd)) {
21065                dumpState.setDump(DumpState.DUMP_INSTALLS);
21066            } else if ("frozen".equals(cmd)) {
21067                dumpState.setDump(DumpState.DUMP_FROZEN);
21068            } else if ("volumes".equals(cmd)) {
21069                dumpState.setDump(DumpState.DUMP_VOLUMES);
21070            } else if ("dexopt".equals(cmd)) {
21071                dumpState.setDump(DumpState.DUMP_DEXOPT);
21072            } else if ("compiler-stats".equals(cmd)) {
21073                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21074            } else if ("changes".equals(cmd)) {
21075                dumpState.setDump(DumpState.DUMP_CHANGES);
21076            } else if ("service-permissions".equals(cmd)) {
21077                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21078            } else if ("write".equals(cmd)) {
21079                synchronized (mPackages) {
21080                    mSettings.writeLPr();
21081                    pw.println("Settings written.");
21082                    return;
21083                }
21084            }
21085        }
21086
21087        if (checkin) {
21088            pw.println("vers,1");
21089        }
21090
21091        // reader
21092        synchronized (mPackages) {
21093            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21094                if (!checkin) {
21095                    if (dumpState.onTitlePrinted())
21096                        pw.println();
21097                    pw.println("Database versions:");
21098                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21099                }
21100            }
21101
21102            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21103                if (!checkin) {
21104                    if (dumpState.onTitlePrinted())
21105                        pw.println();
21106                    pw.println("Verifiers:");
21107                    pw.print("  Required: ");
21108                    pw.print(mRequiredVerifierPackage);
21109                    pw.print(" (uid=");
21110                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21111                            UserHandle.USER_SYSTEM));
21112                    pw.println(")");
21113                } else if (mRequiredVerifierPackage != null) {
21114                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21115                    pw.print(",");
21116                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21117                            UserHandle.USER_SYSTEM));
21118                }
21119            }
21120
21121            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21122                    packageName == null) {
21123                if (mIntentFilterVerifierComponent != null) {
21124                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21125                    if (!checkin) {
21126                        if (dumpState.onTitlePrinted())
21127                            pw.println();
21128                        pw.println("Intent Filter Verifier:");
21129                        pw.print("  Using: ");
21130                        pw.print(verifierPackageName);
21131                        pw.print(" (uid=");
21132                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21133                                UserHandle.USER_SYSTEM));
21134                        pw.println(")");
21135                    } else if (verifierPackageName != null) {
21136                        pw.print("ifv,"); pw.print(verifierPackageName);
21137                        pw.print(",");
21138                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21139                                UserHandle.USER_SYSTEM));
21140                    }
21141                } else {
21142                    pw.println();
21143                    pw.println("No Intent Filter Verifier available!");
21144                }
21145            }
21146
21147            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21148                boolean printedHeader = false;
21149                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21150                while (it.hasNext()) {
21151                    String libName = it.next();
21152                    LongSparseArray<SharedLibraryEntry> versionedLib
21153                            = mSharedLibraries.get(libName);
21154                    if (versionedLib == null) {
21155                        continue;
21156                    }
21157                    final int versionCount = versionedLib.size();
21158                    for (int i = 0; i < versionCount; i++) {
21159                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21160                        if (!checkin) {
21161                            if (!printedHeader) {
21162                                if (dumpState.onTitlePrinted())
21163                                    pw.println();
21164                                pw.println("Libraries:");
21165                                printedHeader = true;
21166                            }
21167                            pw.print("  ");
21168                        } else {
21169                            pw.print("lib,");
21170                        }
21171                        pw.print(libEntry.info.getName());
21172                        if (libEntry.info.isStatic()) {
21173                            pw.print(" version=" + libEntry.info.getLongVersion());
21174                        }
21175                        if (!checkin) {
21176                            pw.print(" -> ");
21177                        }
21178                        if (libEntry.path != null) {
21179                            pw.print(" (jar) ");
21180                            pw.print(libEntry.path);
21181                        } else {
21182                            pw.print(" (apk) ");
21183                            pw.print(libEntry.apk);
21184                        }
21185                        pw.println();
21186                    }
21187                }
21188            }
21189
21190            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21191                if (dumpState.onTitlePrinted())
21192                    pw.println();
21193                if (!checkin) {
21194                    pw.println("Features:");
21195                }
21196
21197                synchronized (mAvailableFeatures) {
21198                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21199                        if (checkin) {
21200                            pw.print("feat,");
21201                            pw.print(feat.name);
21202                            pw.print(",");
21203                            pw.println(feat.version);
21204                        } else {
21205                            pw.print("  ");
21206                            pw.print(feat.name);
21207                            if (feat.version > 0) {
21208                                pw.print(" version=");
21209                                pw.print(feat.version);
21210                            }
21211                            pw.println();
21212                        }
21213                    }
21214                }
21215            }
21216
21217            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21218                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21219                        : "Activity Resolver Table:", "  ", packageName,
21220                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21221                    dumpState.setTitlePrinted(true);
21222                }
21223            }
21224            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21225                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21226                        : "Receiver Resolver Table:", "  ", packageName,
21227                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21228                    dumpState.setTitlePrinted(true);
21229                }
21230            }
21231            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21232                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21233                        : "Service Resolver Table:", "  ", packageName,
21234                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21235                    dumpState.setTitlePrinted(true);
21236                }
21237            }
21238            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21239                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21240                        : "Provider Resolver Table:", "  ", packageName,
21241                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21242                    dumpState.setTitlePrinted(true);
21243                }
21244            }
21245
21246            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21247                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21248                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21249                    int user = mSettings.mPreferredActivities.keyAt(i);
21250                    if (pir.dump(pw,
21251                            dumpState.getTitlePrinted()
21252                                ? "\nPreferred Activities User " + user + ":"
21253                                : "Preferred Activities User " + user + ":", "  ",
21254                            packageName, true, false)) {
21255                        dumpState.setTitlePrinted(true);
21256                    }
21257                }
21258            }
21259
21260            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21261                pw.flush();
21262                FileOutputStream fout = new FileOutputStream(fd);
21263                BufferedOutputStream str = new BufferedOutputStream(fout);
21264                XmlSerializer serializer = new FastXmlSerializer();
21265                try {
21266                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21267                    serializer.startDocument(null, true);
21268                    serializer.setFeature(
21269                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21270                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21271                    serializer.endDocument();
21272                    serializer.flush();
21273                } catch (IllegalArgumentException e) {
21274                    pw.println("Failed writing: " + e);
21275                } catch (IllegalStateException e) {
21276                    pw.println("Failed writing: " + e);
21277                } catch (IOException e) {
21278                    pw.println("Failed writing: " + e);
21279                }
21280            }
21281
21282            if (!checkin
21283                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21284                    && packageName == null) {
21285                pw.println();
21286                int count = mSettings.mPackages.size();
21287                if (count == 0) {
21288                    pw.println("No applications!");
21289                    pw.println();
21290                } else {
21291                    final String prefix = "  ";
21292                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21293                    if (allPackageSettings.size() == 0) {
21294                        pw.println("No domain preferred apps!");
21295                        pw.println();
21296                    } else {
21297                        pw.println("App verification status:");
21298                        pw.println();
21299                        count = 0;
21300                        for (PackageSetting ps : allPackageSettings) {
21301                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21302                            if (ivi == null || ivi.getPackageName() == null) continue;
21303                            pw.println(prefix + "Package: " + ivi.getPackageName());
21304                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21305                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21306                            pw.println();
21307                            count++;
21308                        }
21309                        if (count == 0) {
21310                            pw.println(prefix + "No app verification established.");
21311                            pw.println();
21312                        }
21313                        for (int userId : sUserManager.getUserIds()) {
21314                            pw.println("App linkages for user " + userId + ":");
21315                            pw.println();
21316                            count = 0;
21317                            for (PackageSetting ps : allPackageSettings) {
21318                                final long status = ps.getDomainVerificationStatusForUser(userId);
21319                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21320                                        && !DEBUG_DOMAIN_VERIFICATION) {
21321                                    continue;
21322                                }
21323                                pw.println(prefix + "Package: " + ps.name);
21324                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21325                                String statusStr = IntentFilterVerificationInfo.
21326                                        getStatusStringFromValue(status);
21327                                pw.println(prefix + "Status:  " + statusStr);
21328                                pw.println();
21329                                count++;
21330                            }
21331                            if (count == 0) {
21332                                pw.println(prefix + "No configured app linkages.");
21333                                pw.println();
21334                            }
21335                        }
21336                    }
21337                }
21338            }
21339
21340            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21341                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21342            }
21343
21344            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21345                boolean printedSomething = false;
21346                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21347                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21348                        continue;
21349                    }
21350                    if (!printedSomething) {
21351                        if (dumpState.onTitlePrinted())
21352                            pw.println();
21353                        pw.println("Registered ContentProviders:");
21354                        printedSomething = true;
21355                    }
21356                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21357                    pw.print("    "); pw.println(p.toString());
21358                }
21359                printedSomething = false;
21360                for (Map.Entry<String, PackageParser.Provider> entry :
21361                        mProvidersByAuthority.entrySet()) {
21362                    PackageParser.Provider p = entry.getValue();
21363                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21364                        continue;
21365                    }
21366                    if (!printedSomething) {
21367                        if (dumpState.onTitlePrinted())
21368                            pw.println();
21369                        pw.println("ContentProvider Authorities:");
21370                        printedSomething = true;
21371                    }
21372                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21373                    pw.print("    "); pw.println(p.toString());
21374                    if (p.info != null && p.info.applicationInfo != null) {
21375                        final String appInfo = p.info.applicationInfo.toString();
21376                        pw.print("      applicationInfo="); pw.println(appInfo);
21377                    }
21378                }
21379            }
21380
21381            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21382                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21383            }
21384
21385            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21386                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21387            }
21388
21389            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21390                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21391            }
21392
21393            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21394                if (dumpState.onTitlePrinted()) pw.println();
21395                pw.println("Package Changes:");
21396                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21397                final int K = mChangedPackages.size();
21398                for (int i = 0; i < K; i++) {
21399                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21400                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21401                    final int N = changes.size();
21402                    if (N == 0) {
21403                        pw.print("    "); pw.println("No packages changed");
21404                    } else {
21405                        for (int j = 0; j < N; j++) {
21406                            final String pkgName = changes.valueAt(j);
21407                            final int sequenceNumber = changes.keyAt(j);
21408                            pw.print("    ");
21409                            pw.print("seq=");
21410                            pw.print(sequenceNumber);
21411                            pw.print(", package=");
21412                            pw.println(pkgName);
21413                        }
21414                    }
21415                }
21416            }
21417
21418            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21419                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21420            }
21421
21422            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21423                // XXX should handle packageName != null by dumping only install data that
21424                // the given package is involved with.
21425                if (dumpState.onTitlePrinted()) pw.println();
21426
21427                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21428                ipw.println();
21429                ipw.println("Frozen packages:");
21430                ipw.increaseIndent();
21431                if (mFrozenPackages.size() == 0) {
21432                    ipw.println("(none)");
21433                } else {
21434                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21435                        ipw.println(mFrozenPackages.valueAt(i));
21436                    }
21437                }
21438                ipw.decreaseIndent();
21439            }
21440
21441            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21442                if (dumpState.onTitlePrinted()) pw.println();
21443
21444                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21445                ipw.println();
21446                ipw.println("Loaded volumes:");
21447                ipw.increaseIndent();
21448                if (mLoadedVolumes.size() == 0) {
21449                    ipw.println("(none)");
21450                } else {
21451                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21452                        ipw.println(mLoadedVolumes.valueAt(i));
21453                    }
21454                }
21455                ipw.decreaseIndent();
21456            }
21457
21458            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21459                    && packageName == null) {
21460                if (dumpState.onTitlePrinted()) pw.println();
21461                pw.println("Service permissions:");
21462
21463                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21464                while (filterIterator.hasNext()) {
21465                    final ServiceIntentInfo info = filterIterator.next();
21466                    final ServiceInfo serviceInfo = info.service.info;
21467                    final String permission = serviceInfo.permission;
21468                    if (permission != null) {
21469                        pw.print("    ");
21470                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21471                        pw.print(": ");
21472                        pw.println(permission);
21473                    }
21474                }
21475            }
21476
21477            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21478                if (dumpState.onTitlePrinted()) pw.println();
21479                dumpDexoptStateLPr(pw, packageName);
21480            }
21481
21482            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21483                if (dumpState.onTitlePrinted()) pw.println();
21484                dumpCompilerStatsLPr(pw, packageName);
21485            }
21486
21487            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21488                if (dumpState.onTitlePrinted()) pw.println();
21489                mSettings.dumpReadMessagesLPr(pw, dumpState);
21490
21491                pw.println();
21492                pw.println("Package warning messages:");
21493                dumpCriticalInfo(pw, null);
21494            }
21495
21496            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21497                dumpCriticalInfo(pw, "msg,");
21498            }
21499        }
21500
21501        // PackageInstaller should be called outside of mPackages lock
21502        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21503            // XXX should handle packageName != null by dumping only install data that
21504            // the given package is involved with.
21505            if (dumpState.onTitlePrinted()) pw.println();
21506            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21507        }
21508    }
21509
21510    private void dumpProto(FileDescriptor fd) {
21511        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21512
21513        synchronized (mPackages) {
21514            final long requiredVerifierPackageToken =
21515                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21516            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21517            proto.write(
21518                    PackageServiceDumpProto.PackageShortProto.UID,
21519                    getPackageUid(
21520                            mRequiredVerifierPackage,
21521                            MATCH_DEBUG_TRIAGED_MISSING,
21522                            UserHandle.USER_SYSTEM));
21523            proto.end(requiredVerifierPackageToken);
21524
21525            if (mIntentFilterVerifierComponent != null) {
21526                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21527                final long verifierPackageToken =
21528                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21529                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21530                proto.write(
21531                        PackageServiceDumpProto.PackageShortProto.UID,
21532                        getPackageUid(
21533                                verifierPackageName,
21534                                MATCH_DEBUG_TRIAGED_MISSING,
21535                                UserHandle.USER_SYSTEM));
21536                proto.end(verifierPackageToken);
21537            }
21538
21539            dumpSharedLibrariesProto(proto);
21540            dumpFeaturesProto(proto);
21541            mSettings.dumpPackagesProto(proto);
21542            mSettings.dumpSharedUsersProto(proto);
21543            dumpCriticalInfo(proto);
21544        }
21545        proto.flush();
21546    }
21547
21548    private void dumpFeaturesProto(ProtoOutputStream proto) {
21549        synchronized (mAvailableFeatures) {
21550            final int count = mAvailableFeatures.size();
21551            for (int i = 0; i < count; i++) {
21552                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21553            }
21554        }
21555    }
21556
21557    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21558        final int count = mSharedLibraries.size();
21559        for (int i = 0; i < count; i++) {
21560            final String libName = mSharedLibraries.keyAt(i);
21561            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21562            if (versionedLib == null) {
21563                continue;
21564            }
21565            final int versionCount = versionedLib.size();
21566            for (int j = 0; j < versionCount; j++) {
21567                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21568                final long sharedLibraryToken =
21569                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21570                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21571                final boolean isJar = (libEntry.path != null);
21572                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21573                if (isJar) {
21574                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21575                } else {
21576                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21577                }
21578                proto.end(sharedLibraryToken);
21579            }
21580        }
21581    }
21582
21583    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21584        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21585        ipw.println();
21586        ipw.println("Dexopt state:");
21587        ipw.increaseIndent();
21588        Collection<PackageParser.Package> packages = null;
21589        if (packageName != null) {
21590            PackageParser.Package targetPackage = mPackages.get(packageName);
21591            if (targetPackage != null) {
21592                packages = Collections.singletonList(targetPackage);
21593            } else {
21594                ipw.println("Unable to find package: " + packageName);
21595                return;
21596            }
21597        } else {
21598            packages = mPackages.values();
21599        }
21600
21601        for (PackageParser.Package pkg : packages) {
21602            ipw.println("[" + pkg.packageName + "]");
21603            ipw.increaseIndent();
21604            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21605                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21606            ipw.decreaseIndent();
21607        }
21608    }
21609
21610    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21611        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21612        ipw.println();
21613        ipw.println("Compiler stats:");
21614        ipw.increaseIndent();
21615        Collection<PackageParser.Package> packages = null;
21616        if (packageName != null) {
21617            PackageParser.Package targetPackage = mPackages.get(packageName);
21618            if (targetPackage != null) {
21619                packages = Collections.singletonList(targetPackage);
21620            } else {
21621                ipw.println("Unable to find package: " + packageName);
21622                return;
21623            }
21624        } else {
21625            packages = mPackages.values();
21626        }
21627
21628        for (PackageParser.Package pkg : packages) {
21629            ipw.println("[" + pkg.packageName + "]");
21630            ipw.increaseIndent();
21631
21632            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21633            if (stats == null) {
21634                ipw.println("(No recorded stats)");
21635            } else {
21636                stats.dump(ipw);
21637            }
21638            ipw.decreaseIndent();
21639        }
21640    }
21641
21642    private String dumpDomainString(String packageName) {
21643        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21644                .getList();
21645        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21646
21647        ArraySet<String> result = new ArraySet<>();
21648        if (iviList.size() > 0) {
21649            for (IntentFilterVerificationInfo ivi : iviList) {
21650                for (String host : ivi.getDomains()) {
21651                    result.add(host);
21652                }
21653            }
21654        }
21655        if (filters != null && filters.size() > 0) {
21656            for (IntentFilter filter : filters) {
21657                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21658                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21659                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21660                    result.addAll(filter.getHostsList());
21661                }
21662            }
21663        }
21664
21665        StringBuilder sb = new StringBuilder(result.size() * 16);
21666        for (String domain : result) {
21667            if (sb.length() > 0) sb.append(" ");
21668            sb.append(domain);
21669        }
21670        return sb.toString();
21671    }
21672
21673    // ------- apps on sdcard specific code -------
21674    static final boolean DEBUG_SD_INSTALL = false;
21675
21676    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21677
21678    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21679
21680    private boolean mMediaMounted = false;
21681
21682    static String getEncryptKey() {
21683        try {
21684            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21685                    SD_ENCRYPTION_KEYSTORE_NAME);
21686            if (sdEncKey == null) {
21687                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21688                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21689                if (sdEncKey == null) {
21690                    Slog.e(TAG, "Failed to create encryption keys");
21691                    return null;
21692                }
21693            }
21694            return sdEncKey;
21695        } catch (NoSuchAlgorithmException nsae) {
21696            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21697            return null;
21698        } catch (IOException ioe) {
21699            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21700            return null;
21701        }
21702    }
21703
21704    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21705            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21706        final int size = infos.size();
21707        final String[] packageNames = new String[size];
21708        final int[] packageUids = new int[size];
21709        for (int i = 0; i < size; i++) {
21710            final ApplicationInfo info = infos.get(i);
21711            packageNames[i] = info.packageName;
21712            packageUids[i] = info.uid;
21713        }
21714        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21715                finishedReceiver);
21716    }
21717
21718    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21719            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21720        sendResourcesChangedBroadcast(mediaStatus, replacing,
21721                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21722    }
21723
21724    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21725            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21726        int size = pkgList.length;
21727        if (size > 0) {
21728            // Send broadcasts here
21729            Bundle extras = new Bundle();
21730            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21731            if (uidArr != null) {
21732                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21733            }
21734            if (replacing) {
21735                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21736            }
21737            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21738                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21739            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21740        }
21741    }
21742
21743    private void loadPrivatePackages(final VolumeInfo vol) {
21744        mHandler.post(new Runnable() {
21745            @Override
21746            public void run() {
21747                loadPrivatePackagesInner(vol);
21748            }
21749        });
21750    }
21751
21752    private void loadPrivatePackagesInner(VolumeInfo vol) {
21753        final String volumeUuid = vol.fsUuid;
21754        if (TextUtils.isEmpty(volumeUuid)) {
21755            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21756            return;
21757        }
21758
21759        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21760        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21761        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21762
21763        final VersionInfo ver;
21764        final List<PackageSetting> packages;
21765        synchronized (mPackages) {
21766            ver = mSettings.findOrCreateVersion(volumeUuid);
21767            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21768        }
21769
21770        for (PackageSetting ps : packages) {
21771            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21772            synchronized (mInstallLock) {
21773                final PackageParser.Package pkg;
21774                try {
21775                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21776                    loaded.add(pkg.applicationInfo);
21777
21778                } catch (PackageManagerException e) {
21779                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21780                }
21781
21782                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21783                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21784                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21785                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21786                }
21787            }
21788        }
21789
21790        // Reconcile app data for all started/unlocked users
21791        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21792        final UserManager um = mContext.getSystemService(UserManager.class);
21793        UserManagerInternal umInternal = getUserManagerInternal();
21794        for (UserInfo user : um.getUsers()) {
21795            final int flags;
21796            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21797                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21798            } else if (umInternal.isUserRunning(user.id)) {
21799                flags = StorageManager.FLAG_STORAGE_DE;
21800            } else {
21801                continue;
21802            }
21803
21804            try {
21805                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21806                synchronized (mInstallLock) {
21807                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21808                }
21809            } catch (IllegalStateException e) {
21810                // Device was probably ejected, and we'll process that event momentarily
21811                Slog.w(TAG, "Failed to prepare storage: " + e);
21812            }
21813        }
21814
21815        synchronized (mPackages) {
21816            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21817            if (sdkUpdated) {
21818                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21819                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21820            }
21821            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21822                    mPermissionCallback);
21823
21824            // Yay, everything is now upgraded
21825            ver.forceCurrent();
21826
21827            mSettings.writeLPr();
21828        }
21829
21830        for (PackageFreezer freezer : freezers) {
21831            freezer.close();
21832        }
21833
21834        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21835        sendResourcesChangedBroadcast(true, false, loaded, null);
21836        mLoadedVolumes.add(vol.getId());
21837    }
21838
21839    private void unloadPrivatePackages(final VolumeInfo vol) {
21840        mHandler.post(new Runnable() {
21841            @Override
21842            public void run() {
21843                unloadPrivatePackagesInner(vol);
21844            }
21845        });
21846    }
21847
21848    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21849        final String volumeUuid = vol.fsUuid;
21850        if (TextUtils.isEmpty(volumeUuid)) {
21851            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21852            return;
21853        }
21854
21855        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21856        synchronized (mInstallLock) {
21857        synchronized (mPackages) {
21858            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21859            for (PackageSetting ps : packages) {
21860                if (ps.pkg == null) continue;
21861
21862                final ApplicationInfo info = ps.pkg.applicationInfo;
21863                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21864                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21865
21866                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21867                        "unloadPrivatePackagesInner")) {
21868                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21869                            false, null)) {
21870                        unloaded.add(info);
21871                    } else {
21872                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21873                    }
21874                }
21875
21876                // Try very hard to release any references to this package
21877                // so we don't risk the system server being killed due to
21878                // open FDs
21879                AttributeCache.instance().removePackage(ps.name);
21880            }
21881
21882            mSettings.writeLPr();
21883        }
21884        }
21885
21886        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21887        sendResourcesChangedBroadcast(false, false, unloaded, null);
21888        mLoadedVolumes.remove(vol.getId());
21889
21890        // Try very hard to release any references to this path so we don't risk
21891        // the system server being killed due to open FDs
21892        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21893
21894        for (int i = 0; i < 3; i++) {
21895            System.gc();
21896            System.runFinalization();
21897        }
21898    }
21899
21900    private void assertPackageKnown(String volumeUuid, String packageName)
21901            throws PackageManagerException {
21902        synchronized (mPackages) {
21903            // Normalize package name to handle renamed packages
21904            packageName = normalizePackageNameLPr(packageName);
21905
21906            final PackageSetting ps = mSettings.mPackages.get(packageName);
21907            if (ps == null) {
21908                throw new PackageManagerException("Package " + packageName + " is unknown");
21909            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21910                throw new PackageManagerException(
21911                        "Package " + packageName + " found on unknown volume " + volumeUuid
21912                                + "; expected volume " + ps.volumeUuid);
21913            }
21914        }
21915    }
21916
21917    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21918            throws PackageManagerException {
21919        synchronized (mPackages) {
21920            // Normalize package name to handle renamed packages
21921            packageName = normalizePackageNameLPr(packageName);
21922
21923            final PackageSetting ps = mSettings.mPackages.get(packageName);
21924            if (ps == null) {
21925                throw new PackageManagerException("Package " + packageName + " is unknown");
21926            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21927                throw new PackageManagerException(
21928                        "Package " + packageName + " found on unknown volume " + volumeUuid
21929                                + "; expected volume " + ps.volumeUuid);
21930            } else if (!ps.getInstalled(userId)) {
21931                throw new PackageManagerException(
21932                        "Package " + packageName + " not installed for user " + userId);
21933            }
21934        }
21935    }
21936
21937    private List<String> collectAbsoluteCodePaths() {
21938        synchronized (mPackages) {
21939            List<String> codePaths = new ArrayList<>();
21940            final int packageCount = mSettings.mPackages.size();
21941            for (int i = 0; i < packageCount; i++) {
21942                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21943                codePaths.add(ps.codePath.getAbsolutePath());
21944            }
21945            return codePaths;
21946        }
21947    }
21948
21949    /**
21950     * Examine all apps present on given mounted volume, and destroy apps that
21951     * aren't expected, either due to uninstallation or reinstallation on
21952     * another volume.
21953     */
21954    private void reconcileApps(String volumeUuid) {
21955        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21956        List<File> filesToDelete = null;
21957
21958        final File[] files = FileUtils.listFilesOrEmpty(
21959                Environment.getDataAppDirectory(volumeUuid));
21960        for (File file : files) {
21961            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21962                    && !PackageInstallerService.isStageName(file.getName());
21963            if (!isPackage) {
21964                // Ignore entries which are not packages
21965                continue;
21966            }
21967
21968            String absolutePath = file.getAbsolutePath();
21969
21970            boolean pathValid = false;
21971            final int absoluteCodePathCount = absoluteCodePaths.size();
21972            for (int i = 0; i < absoluteCodePathCount; i++) {
21973                String absoluteCodePath = absoluteCodePaths.get(i);
21974                if (absolutePath.startsWith(absoluteCodePath)) {
21975                    pathValid = true;
21976                    break;
21977                }
21978            }
21979
21980            if (!pathValid) {
21981                if (filesToDelete == null) {
21982                    filesToDelete = new ArrayList<>();
21983                }
21984                filesToDelete.add(file);
21985            }
21986        }
21987
21988        if (filesToDelete != null) {
21989            final int fileToDeleteCount = filesToDelete.size();
21990            for (int i = 0; i < fileToDeleteCount; i++) {
21991                File fileToDelete = filesToDelete.get(i);
21992                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21993                synchronized (mInstallLock) {
21994                    removeCodePathLI(fileToDelete);
21995                }
21996            }
21997        }
21998    }
21999
22000    /**
22001     * Reconcile all app data for the given user.
22002     * <p>
22003     * Verifies that directories exist and that ownership and labeling is
22004     * correct for all installed apps on all mounted volumes.
22005     */
22006    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22007        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22008        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22009            final String volumeUuid = vol.getFsUuid();
22010            synchronized (mInstallLock) {
22011                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22012            }
22013        }
22014    }
22015
22016    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22017            boolean migrateAppData) {
22018        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22019    }
22020
22021    /**
22022     * Reconcile all app data on given mounted volume.
22023     * <p>
22024     * Destroys app data that isn't expected, either due to uninstallation or
22025     * reinstallation on another volume.
22026     * <p>
22027     * Verifies that directories exist and that ownership and labeling is
22028     * correct for all installed apps.
22029     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22030     */
22031    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22032            boolean migrateAppData, boolean onlyCoreApps) {
22033        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22034                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22035        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22036
22037        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22038        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22039
22040        // First look for stale data that doesn't belong, and check if things
22041        // have changed since we did our last restorecon
22042        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22043            if (StorageManager.isFileEncryptedNativeOrEmulated()
22044                    && !StorageManager.isUserKeyUnlocked(userId)) {
22045                throw new RuntimeException(
22046                        "Yikes, someone asked us to reconcile CE storage while " + userId
22047                                + " was still locked; this would have caused massive data loss!");
22048            }
22049
22050            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22051            for (File file : files) {
22052                final String packageName = file.getName();
22053                try {
22054                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22055                } catch (PackageManagerException e) {
22056                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22057                    try {
22058                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22059                                StorageManager.FLAG_STORAGE_CE, 0);
22060                    } catch (InstallerException e2) {
22061                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22062                    }
22063                }
22064            }
22065        }
22066        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22067            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22068            for (File file : files) {
22069                final String packageName = file.getName();
22070                try {
22071                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22072                } catch (PackageManagerException e) {
22073                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22074                    try {
22075                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22076                                StorageManager.FLAG_STORAGE_DE, 0);
22077                    } catch (InstallerException e2) {
22078                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22079                    }
22080                }
22081            }
22082        }
22083
22084        // Ensure that data directories are ready to roll for all packages
22085        // installed for this volume and user
22086        final List<PackageSetting> packages;
22087        synchronized (mPackages) {
22088            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22089        }
22090        int preparedCount = 0;
22091        for (PackageSetting ps : packages) {
22092            final String packageName = ps.name;
22093            if (ps.pkg == null) {
22094                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22095                // TODO: might be due to legacy ASEC apps; we should circle back
22096                // and reconcile again once they're scanned
22097                continue;
22098            }
22099            // Skip non-core apps if requested
22100            if (onlyCoreApps && !ps.pkg.coreApp) {
22101                result.add(packageName);
22102                continue;
22103            }
22104
22105            if (ps.getInstalled(userId)) {
22106                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22107                preparedCount++;
22108            }
22109        }
22110
22111        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22112        return result;
22113    }
22114
22115    /**
22116     * Prepare app data for the given app just after it was installed or
22117     * upgraded. This method carefully only touches users that it's installed
22118     * for, and it forces a restorecon to handle any seinfo changes.
22119     * <p>
22120     * Verifies that directories exist and that ownership and labeling is
22121     * correct for all installed apps. If there is an ownership mismatch, it
22122     * will try recovering system apps by wiping data; third-party app data is
22123     * left intact.
22124     * <p>
22125     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22126     */
22127    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22128        final PackageSetting ps;
22129        synchronized (mPackages) {
22130            ps = mSettings.mPackages.get(pkg.packageName);
22131            mSettings.writeKernelMappingLPr(ps);
22132        }
22133
22134        final UserManager um = mContext.getSystemService(UserManager.class);
22135        UserManagerInternal umInternal = getUserManagerInternal();
22136        for (UserInfo user : um.getUsers()) {
22137            final int flags;
22138            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22139                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22140            } else if (umInternal.isUserRunning(user.id)) {
22141                flags = StorageManager.FLAG_STORAGE_DE;
22142            } else {
22143                continue;
22144            }
22145
22146            if (ps.getInstalled(user.id)) {
22147                // TODO: when user data is locked, mark that we're still dirty
22148                prepareAppDataLIF(pkg, user.id, flags);
22149            }
22150        }
22151    }
22152
22153    /**
22154     * Prepare app data for the given app.
22155     * <p>
22156     * Verifies that directories exist and that ownership and labeling is
22157     * correct for all installed apps. If there is an ownership mismatch, this
22158     * will try recovering system apps by wiping data; third-party app data is
22159     * left intact.
22160     */
22161    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22162        if (pkg == null) {
22163            Slog.wtf(TAG, "Package was null!", new Throwable());
22164            return;
22165        }
22166        prepareAppDataLeafLIF(pkg, userId, flags);
22167        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22168        for (int i = 0; i < childCount; i++) {
22169            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22170        }
22171    }
22172
22173    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22174            boolean maybeMigrateAppData) {
22175        prepareAppDataLIF(pkg, userId, flags);
22176
22177        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22178            // We may have just shuffled around app data directories, so
22179            // prepare them one more time
22180            prepareAppDataLIF(pkg, userId, flags);
22181        }
22182    }
22183
22184    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22185        if (DEBUG_APP_DATA) {
22186            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22187                    + Integer.toHexString(flags));
22188        }
22189
22190        final String volumeUuid = pkg.volumeUuid;
22191        final String packageName = pkg.packageName;
22192        final ApplicationInfo app = pkg.applicationInfo;
22193        final int appId = UserHandle.getAppId(app.uid);
22194
22195        Preconditions.checkNotNull(app.seInfo);
22196
22197        long ceDataInode = -1;
22198        try {
22199            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22200                    appId, app.seInfo, app.targetSdkVersion);
22201        } catch (InstallerException e) {
22202            if (app.isSystemApp()) {
22203                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22204                        + ", but trying to recover: " + e);
22205                destroyAppDataLeafLIF(pkg, userId, flags);
22206                try {
22207                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22208                            appId, app.seInfo, app.targetSdkVersion);
22209                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22210                } catch (InstallerException e2) {
22211                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22212                }
22213            } else {
22214                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22215            }
22216        }
22217        // Prepare the application profiles.
22218        mArtManagerService.prepareAppProfiles(pkg, userId);
22219
22220        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22221            // TODO: mark this structure as dirty so we persist it!
22222            synchronized (mPackages) {
22223                final PackageSetting ps = mSettings.mPackages.get(packageName);
22224                if (ps != null) {
22225                    ps.setCeDataInode(ceDataInode, userId);
22226                }
22227            }
22228        }
22229
22230        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22231    }
22232
22233    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22234        if (pkg == null) {
22235            Slog.wtf(TAG, "Package was null!", new Throwable());
22236            return;
22237        }
22238        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22239        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22240        for (int i = 0; i < childCount; i++) {
22241            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22242        }
22243    }
22244
22245    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22246        final String volumeUuid = pkg.volumeUuid;
22247        final String packageName = pkg.packageName;
22248        final ApplicationInfo app = pkg.applicationInfo;
22249
22250        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22251            // Create a native library symlink only if we have native libraries
22252            // and if the native libraries are 32 bit libraries. We do not provide
22253            // this symlink for 64 bit libraries.
22254            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22255                final String nativeLibPath = app.nativeLibraryDir;
22256                try {
22257                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22258                            nativeLibPath, userId);
22259                } catch (InstallerException e) {
22260                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22261                }
22262            }
22263        }
22264    }
22265
22266    /**
22267     * For system apps on non-FBE devices, this method migrates any existing
22268     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22269     * requested by the app.
22270     */
22271    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22272        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22273                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22274            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22275                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22276            try {
22277                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22278                        storageTarget);
22279            } catch (InstallerException e) {
22280                logCriticalInfo(Log.WARN,
22281                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22282            }
22283            return true;
22284        } else {
22285            return false;
22286        }
22287    }
22288
22289    public PackageFreezer freezePackage(String packageName, String killReason) {
22290        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22291    }
22292
22293    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22294        return new PackageFreezer(packageName, userId, killReason);
22295    }
22296
22297    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22298            String killReason) {
22299        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22300    }
22301
22302    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22303            String killReason) {
22304        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22305            return new PackageFreezer();
22306        } else {
22307            return freezePackage(packageName, userId, killReason);
22308        }
22309    }
22310
22311    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22312            String killReason) {
22313        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22314    }
22315
22316    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22317            String killReason) {
22318        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22319            return new PackageFreezer();
22320        } else {
22321            return freezePackage(packageName, userId, killReason);
22322        }
22323    }
22324
22325    /**
22326     * Class that freezes and kills the given package upon creation, and
22327     * unfreezes it upon closing. This is typically used when doing surgery on
22328     * app code/data to prevent the app from running while you're working.
22329     */
22330    private class PackageFreezer implements AutoCloseable {
22331        private final String mPackageName;
22332        private final PackageFreezer[] mChildren;
22333
22334        private final boolean mWeFroze;
22335
22336        private final AtomicBoolean mClosed = new AtomicBoolean();
22337        private final CloseGuard mCloseGuard = CloseGuard.get();
22338
22339        /**
22340         * Create and return a stub freezer that doesn't actually do anything,
22341         * typically used when someone requested
22342         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22343         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22344         */
22345        public PackageFreezer() {
22346            mPackageName = null;
22347            mChildren = null;
22348            mWeFroze = false;
22349            mCloseGuard.open("close");
22350        }
22351
22352        public PackageFreezer(String packageName, int userId, String killReason) {
22353            synchronized (mPackages) {
22354                mPackageName = packageName;
22355                mWeFroze = mFrozenPackages.add(mPackageName);
22356
22357                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22358                if (ps != null) {
22359                    killApplication(ps.name, ps.appId, userId, killReason);
22360                }
22361
22362                final PackageParser.Package p = mPackages.get(packageName);
22363                if (p != null && p.childPackages != null) {
22364                    final int N = p.childPackages.size();
22365                    mChildren = new PackageFreezer[N];
22366                    for (int i = 0; i < N; i++) {
22367                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22368                                userId, killReason);
22369                    }
22370                } else {
22371                    mChildren = null;
22372                }
22373            }
22374            mCloseGuard.open("close");
22375        }
22376
22377        @Override
22378        protected void finalize() throws Throwable {
22379            try {
22380                if (mCloseGuard != null) {
22381                    mCloseGuard.warnIfOpen();
22382                }
22383
22384                close();
22385            } finally {
22386                super.finalize();
22387            }
22388        }
22389
22390        @Override
22391        public void close() {
22392            mCloseGuard.close();
22393            if (mClosed.compareAndSet(false, true)) {
22394                synchronized (mPackages) {
22395                    if (mWeFroze) {
22396                        mFrozenPackages.remove(mPackageName);
22397                    }
22398
22399                    if (mChildren != null) {
22400                        for (PackageFreezer freezer : mChildren) {
22401                            freezer.close();
22402                        }
22403                    }
22404                }
22405            }
22406        }
22407    }
22408
22409    /**
22410     * Verify that given package is currently frozen.
22411     */
22412    private void checkPackageFrozen(String packageName) {
22413        synchronized (mPackages) {
22414            if (!mFrozenPackages.contains(packageName)) {
22415                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22416            }
22417        }
22418    }
22419
22420    @Override
22421    public int movePackage(final String packageName, final String volumeUuid) {
22422        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22423
22424        final int callingUid = Binder.getCallingUid();
22425        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22426        final int moveId = mNextMoveId.getAndIncrement();
22427        mHandler.post(new Runnable() {
22428            @Override
22429            public void run() {
22430                try {
22431                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22432                } catch (PackageManagerException e) {
22433                    Slog.w(TAG, "Failed to move " + packageName, e);
22434                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22435                }
22436            }
22437        });
22438        return moveId;
22439    }
22440
22441    private void movePackageInternal(final String packageName, final String volumeUuid,
22442            final int moveId, final int callingUid, UserHandle user)
22443                    throws PackageManagerException {
22444        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22445        final PackageManager pm = mContext.getPackageManager();
22446
22447        final boolean currentAsec;
22448        final String currentVolumeUuid;
22449        final File codeFile;
22450        final String installerPackageName;
22451        final String packageAbiOverride;
22452        final int appId;
22453        final String seinfo;
22454        final String label;
22455        final int targetSdkVersion;
22456        final PackageFreezer freezer;
22457        final int[] installedUserIds;
22458
22459        // reader
22460        synchronized (mPackages) {
22461            final PackageParser.Package pkg = mPackages.get(packageName);
22462            final PackageSetting ps = mSettings.mPackages.get(packageName);
22463            if (pkg == null
22464                    || ps == null
22465                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22466                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22467            }
22468            if (pkg.applicationInfo.isSystemApp()) {
22469                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22470                        "Cannot move system application");
22471            }
22472
22473            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22474            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22475                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22476            if (isInternalStorage && !allow3rdPartyOnInternal) {
22477                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22478                        "3rd party apps are not allowed on internal storage");
22479            }
22480
22481            if (pkg.applicationInfo.isExternalAsec()) {
22482                currentAsec = true;
22483                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22484            } else if (pkg.applicationInfo.isForwardLocked()) {
22485                currentAsec = true;
22486                currentVolumeUuid = "forward_locked";
22487            } else {
22488                currentAsec = false;
22489                currentVolumeUuid = ps.volumeUuid;
22490
22491                final File probe = new File(pkg.codePath);
22492                final File probeOat = new File(probe, "oat");
22493                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22494                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22495                            "Move only supported for modern cluster style installs");
22496                }
22497            }
22498
22499            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22500                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22501                        "Package already moved to " + volumeUuid);
22502            }
22503            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22504                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22505                        "Device admin cannot be moved");
22506            }
22507
22508            if (mFrozenPackages.contains(packageName)) {
22509                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22510                        "Failed to move already frozen package");
22511            }
22512
22513            codeFile = new File(pkg.codePath);
22514            installerPackageName = ps.installerPackageName;
22515            packageAbiOverride = ps.cpuAbiOverrideString;
22516            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22517            seinfo = pkg.applicationInfo.seInfo;
22518            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22519            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22520            freezer = freezePackage(packageName, "movePackageInternal");
22521            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22522        }
22523
22524        final Bundle extras = new Bundle();
22525        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22526        extras.putString(Intent.EXTRA_TITLE, label);
22527        mMoveCallbacks.notifyCreated(moveId, extras);
22528
22529        int installFlags;
22530        final boolean moveCompleteApp;
22531        final File measurePath;
22532
22533        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22534            installFlags = INSTALL_INTERNAL;
22535            moveCompleteApp = !currentAsec;
22536            measurePath = Environment.getDataAppDirectory(volumeUuid);
22537        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22538            installFlags = INSTALL_EXTERNAL;
22539            moveCompleteApp = false;
22540            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22541        } else {
22542            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22543            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22544                    || !volume.isMountedWritable()) {
22545                freezer.close();
22546                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22547                        "Move location not mounted private volume");
22548            }
22549
22550            Preconditions.checkState(!currentAsec);
22551
22552            installFlags = INSTALL_INTERNAL;
22553            moveCompleteApp = true;
22554            measurePath = Environment.getDataAppDirectory(volumeUuid);
22555        }
22556
22557        // If we're moving app data around, we need all the users unlocked
22558        if (moveCompleteApp) {
22559            for (int userId : installedUserIds) {
22560                if (StorageManager.isFileEncryptedNativeOrEmulated()
22561                        && !StorageManager.isUserKeyUnlocked(userId)) {
22562                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22563                            "User " + userId + " must be unlocked");
22564                }
22565            }
22566        }
22567
22568        final PackageStats stats = new PackageStats(null, -1);
22569        synchronized (mInstaller) {
22570            for (int userId : installedUserIds) {
22571                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22572                    freezer.close();
22573                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22574                            "Failed to measure package size");
22575                }
22576            }
22577        }
22578
22579        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22580                + stats.dataSize);
22581
22582        final long startFreeBytes = measurePath.getUsableSpace();
22583        final long sizeBytes;
22584        if (moveCompleteApp) {
22585            sizeBytes = stats.codeSize + stats.dataSize;
22586        } else {
22587            sizeBytes = stats.codeSize;
22588        }
22589
22590        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22591            freezer.close();
22592            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22593                    "Not enough free space to move");
22594        }
22595
22596        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22597
22598        final CountDownLatch installedLatch = new CountDownLatch(1);
22599        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22600            @Override
22601            public void onUserActionRequired(Intent intent) throws RemoteException {
22602                throw new IllegalStateException();
22603            }
22604
22605            @Override
22606            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22607                    Bundle extras) throws RemoteException {
22608                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22609                        + PackageManager.installStatusToString(returnCode, msg));
22610
22611                installedLatch.countDown();
22612                freezer.close();
22613
22614                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22615                switch (status) {
22616                    case PackageInstaller.STATUS_SUCCESS:
22617                        mMoveCallbacks.notifyStatusChanged(moveId,
22618                                PackageManager.MOVE_SUCCEEDED);
22619                        break;
22620                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22621                        mMoveCallbacks.notifyStatusChanged(moveId,
22622                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22623                        break;
22624                    default:
22625                        mMoveCallbacks.notifyStatusChanged(moveId,
22626                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22627                        break;
22628                }
22629            }
22630        };
22631
22632        final MoveInfo move;
22633        if (moveCompleteApp) {
22634            // Kick off a thread to report progress estimates
22635            new Thread() {
22636                @Override
22637                public void run() {
22638                    while (true) {
22639                        try {
22640                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22641                                break;
22642                            }
22643                        } catch (InterruptedException ignored) {
22644                        }
22645
22646                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22647                        final int progress = 10 + (int) MathUtils.constrain(
22648                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22649                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22650                    }
22651                }
22652            }.start();
22653
22654            final String dataAppName = codeFile.getName();
22655            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22656                    dataAppName, appId, seinfo, targetSdkVersion);
22657        } else {
22658            move = null;
22659        }
22660
22661        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22662
22663        final Message msg = mHandler.obtainMessage(INIT_COPY);
22664        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22665        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22666                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22667                packageAbiOverride, null /*grantedPermissions*/,
22668                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22669        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22670        msg.obj = params;
22671
22672        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22673                System.identityHashCode(msg.obj));
22674        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22675                System.identityHashCode(msg.obj));
22676
22677        mHandler.sendMessage(msg);
22678    }
22679
22680    @Override
22681    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22682        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22683
22684        final int realMoveId = mNextMoveId.getAndIncrement();
22685        final Bundle extras = new Bundle();
22686        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22687        mMoveCallbacks.notifyCreated(realMoveId, extras);
22688
22689        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22690            @Override
22691            public void onCreated(int moveId, Bundle extras) {
22692                // Ignored
22693            }
22694
22695            @Override
22696            public void onStatusChanged(int moveId, int status, long estMillis) {
22697                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22698            }
22699        };
22700
22701        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22702        storage.setPrimaryStorageUuid(volumeUuid, callback);
22703        return realMoveId;
22704    }
22705
22706    @Override
22707    public int getMoveStatus(int moveId) {
22708        mContext.enforceCallingOrSelfPermission(
22709                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22710        return mMoveCallbacks.mLastStatus.get(moveId);
22711    }
22712
22713    @Override
22714    public void registerMoveCallback(IPackageMoveObserver callback) {
22715        mContext.enforceCallingOrSelfPermission(
22716                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22717        mMoveCallbacks.register(callback);
22718    }
22719
22720    @Override
22721    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22722        mContext.enforceCallingOrSelfPermission(
22723                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22724        mMoveCallbacks.unregister(callback);
22725    }
22726
22727    @Override
22728    public boolean setInstallLocation(int loc) {
22729        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22730                null);
22731        if (getInstallLocation() == loc) {
22732            return true;
22733        }
22734        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22735                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22736            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22737                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22738            return true;
22739        }
22740        return false;
22741   }
22742
22743    @Override
22744    public int getInstallLocation() {
22745        // allow instant app access
22746        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22747                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22748                PackageHelper.APP_INSTALL_AUTO);
22749    }
22750
22751    /** Called by UserManagerService */
22752    void cleanUpUser(UserManagerService userManager, int userHandle) {
22753        synchronized (mPackages) {
22754            mDirtyUsers.remove(userHandle);
22755            mUserNeedsBadging.delete(userHandle);
22756            mSettings.removeUserLPw(userHandle);
22757            mPendingBroadcasts.remove(userHandle);
22758            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22759            removeUnusedPackagesLPw(userManager, userHandle);
22760        }
22761    }
22762
22763    /**
22764     * We're removing userHandle and would like to remove any downloaded packages
22765     * that are no longer in use by any other user.
22766     * @param userHandle the user being removed
22767     */
22768    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22769        final boolean DEBUG_CLEAN_APKS = false;
22770        int [] users = userManager.getUserIds();
22771        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22772        while (psit.hasNext()) {
22773            PackageSetting ps = psit.next();
22774            if (ps.pkg == null) {
22775                continue;
22776            }
22777            final String packageName = ps.pkg.packageName;
22778            // Skip over if system app
22779            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22780                continue;
22781            }
22782            if (DEBUG_CLEAN_APKS) {
22783                Slog.i(TAG, "Checking package " + packageName);
22784            }
22785            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22786            if (keep) {
22787                if (DEBUG_CLEAN_APKS) {
22788                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22789                }
22790            } else {
22791                for (int i = 0; i < users.length; i++) {
22792                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22793                        keep = true;
22794                        if (DEBUG_CLEAN_APKS) {
22795                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22796                                    + users[i]);
22797                        }
22798                        break;
22799                    }
22800                }
22801            }
22802            if (!keep) {
22803                if (DEBUG_CLEAN_APKS) {
22804                    Slog.i(TAG, "  Removing package " + packageName);
22805                }
22806                mHandler.post(new Runnable() {
22807                    public void run() {
22808                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22809                                userHandle, 0);
22810                    } //end run
22811                });
22812            }
22813        }
22814    }
22815
22816    /** Called by UserManagerService */
22817    void createNewUser(int userId, String[] disallowedPackages) {
22818        synchronized (mInstallLock) {
22819            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22820        }
22821        synchronized (mPackages) {
22822            scheduleWritePackageRestrictionsLocked(userId);
22823            scheduleWritePackageListLocked(userId);
22824            applyFactoryDefaultBrowserLPw(userId);
22825            primeDomainVerificationsLPw(userId);
22826        }
22827    }
22828
22829    void onNewUserCreated(final int userId) {
22830        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22831        synchronized(mPackages) {
22832            // If permission review for legacy apps is required, we represent
22833            // dagerous permissions for such apps as always granted runtime
22834            // permissions to keep per user flag state whether review is needed.
22835            // Hence, if a new user is added we have to propagate dangerous
22836            // permission grants for these legacy apps.
22837            if (mSettings.mPermissions.mPermissionReviewRequired) {
22838// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22839                mPermissionManager.updateAllPermissions(
22840                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22841                        mPermissionCallback);
22842            }
22843        }
22844    }
22845
22846    @Override
22847    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22848        mContext.enforceCallingOrSelfPermission(
22849                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22850                "Only package verification agents can read the verifier device identity");
22851
22852        synchronized (mPackages) {
22853            return mSettings.getVerifierDeviceIdentityLPw();
22854        }
22855    }
22856
22857    @Override
22858    public void setPermissionEnforced(String permission, boolean enforced) {
22859        // TODO: Now that we no longer change GID for storage, this should to away.
22860        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22861                "setPermissionEnforced");
22862        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22863            synchronized (mPackages) {
22864                if (mSettings.mReadExternalStorageEnforced == null
22865                        || mSettings.mReadExternalStorageEnforced != enforced) {
22866                    mSettings.mReadExternalStorageEnforced =
22867                            enforced ? Boolean.TRUE : Boolean.FALSE;
22868                    mSettings.writeLPr();
22869                }
22870            }
22871            // kill any non-foreground processes so we restart them and
22872            // grant/revoke the GID.
22873            final IActivityManager am = ActivityManager.getService();
22874            if (am != null) {
22875                final long token = Binder.clearCallingIdentity();
22876                try {
22877                    am.killProcessesBelowForeground("setPermissionEnforcement");
22878                } catch (RemoteException e) {
22879                } finally {
22880                    Binder.restoreCallingIdentity(token);
22881                }
22882            }
22883        } else {
22884            throw new IllegalArgumentException("No selective enforcement for " + permission);
22885        }
22886    }
22887
22888    @Override
22889    @Deprecated
22890    public boolean isPermissionEnforced(String permission) {
22891        // allow instant applications
22892        return true;
22893    }
22894
22895    @Override
22896    public boolean isStorageLow() {
22897        // allow instant applications
22898        final long token = Binder.clearCallingIdentity();
22899        try {
22900            final DeviceStorageMonitorInternal
22901                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22902            if (dsm != null) {
22903                return dsm.isMemoryLow();
22904            } else {
22905                return false;
22906            }
22907        } finally {
22908            Binder.restoreCallingIdentity(token);
22909        }
22910    }
22911
22912    @Override
22913    public IPackageInstaller getPackageInstaller() {
22914        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22915            return null;
22916        }
22917        return mInstallerService;
22918    }
22919
22920    @Override
22921    public IArtManager getArtManager() {
22922        return mArtManagerService;
22923    }
22924
22925    private boolean userNeedsBadging(int userId) {
22926        int index = mUserNeedsBadging.indexOfKey(userId);
22927        if (index < 0) {
22928            final UserInfo userInfo;
22929            final long token = Binder.clearCallingIdentity();
22930            try {
22931                userInfo = sUserManager.getUserInfo(userId);
22932            } finally {
22933                Binder.restoreCallingIdentity(token);
22934            }
22935            final boolean b;
22936            if (userInfo != null && userInfo.isManagedProfile()) {
22937                b = true;
22938            } else {
22939                b = false;
22940            }
22941            mUserNeedsBadging.put(userId, b);
22942            return b;
22943        }
22944        return mUserNeedsBadging.valueAt(index);
22945    }
22946
22947    @Override
22948    public KeySet getKeySetByAlias(String packageName, String alias) {
22949        if (packageName == null || alias == null) {
22950            return null;
22951        }
22952        synchronized(mPackages) {
22953            final PackageParser.Package pkg = mPackages.get(packageName);
22954            if (pkg == null) {
22955                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22956                throw new IllegalArgumentException("Unknown package: " + packageName);
22957            }
22958            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22959            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22960                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22961                throw new IllegalArgumentException("Unknown package: " + packageName);
22962            }
22963            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22964            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22965        }
22966    }
22967
22968    @Override
22969    public KeySet getSigningKeySet(String packageName) {
22970        if (packageName == null) {
22971            return null;
22972        }
22973        synchronized(mPackages) {
22974            final int callingUid = Binder.getCallingUid();
22975            final int callingUserId = UserHandle.getUserId(callingUid);
22976            final PackageParser.Package pkg = mPackages.get(packageName);
22977            if (pkg == null) {
22978                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22979                throw new IllegalArgumentException("Unknown package: " + packageName);
22980            }
22981            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22982            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
22983                // filter and pretend the package doesn't exist
22984                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
22985                        + ", uid:" + callingUid);
22986                throw new IllegalArgumentException("Unknown package: " + packageName);
22987            }
22988            if (pkg.applicationInfo.uid != callingUid
22989                    && Process.SYSTEM_UID != callingUid) {
22990                throw new SecurityException("May not access signing KeySet of other apps.");
22991            }
22992            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22993            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22994        }
22995    }
22996
22997    @Override
22998    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22999        final int callingUid = Binder.getCallingUid();
23000        if (getInstantAppPackageName(callingUid) != null) {
23001            return false;
23002        }
23003        if (packageName == null || ks == null) {
23004            return false;
23005        }
23006        synchronized(mPackages) {
23007            final PackageParser.Package pkg = mPackages.get(packageName);
23008            if (pkg == null
23009                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23010                            UserHandle.getUserId(callingUid))) {
23011                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23012                throw new IllegalArgumentException("Unknown package: " + packageName);
23013            }
23014            IBinder ksh = ks.getToken();
23015            if (ksh instanceof KeySetHandle) {
23016                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23017                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23018            }
23019            return false;
23020        }
23021    }
23022
23023    @Override
23024    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23025        final int callingUid = Binder.getCallingUid();
23026        if (getInstantAppPackageName(callingUid) != null) {
23027            return false;
23028        }
23029        if (packageName == null || ks == null) {
23030            return false;
23031        }
23032        synchronized(mPackages) {
23033            final PackageParser.Package pkg = mPackages.get(packageName);
23034            if (pkg == null
23035                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23036                            UserHandle.getUserId(callingUid))) {
23037                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23038                throw new IllegalArgumentException("Unknown package: " + packageName);
23039            }
23040            IBinder ksh = ks.getToken();
23041            if (ksh instanceof KeySetHandle) {
23042                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23043                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23044            }
23045            return false;
23046        }
23047    }
23048
23049    private void deletePackageIfUnusedLPr(final String packageName) {
23050        PackageSetting ps = mSettings.mPackages.get(packageName);
23051        if (ps == null) {
23052            return;
23053        }
23054        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23055            // TODO Implement atomic delete if package is unused
23056            // It is currently possible that the package will be deleted even if it is installed
23057            // after this method returns.
23058            mHandler.post(new Runnable() {
23059                public void run() {
23060                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23061                            0, PackageManager.DELETE_ALL_USERS);
23062                }
23063            });
23064        }
23065    }
23066
23067    /**
23068     * Check and throw if the given before/after packages would be considered a
23069     * downgrade.
23070     */
23071    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23072            throws PackageManagerException {
23073        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23074            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23075                    "Update version code " + after.versionCode + " is older than current "
23076                    + before.getLongVersionCode());
23077        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23078            if (after.baseRevisionCode < before.baseRevisionCode) {
23079                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23080                        "Update base revision code " + after.baseRevisionCode
23081                        + " is older than current " + before.baseRevisionCode);
23082            }
23083
23084            if (!ArrayUtils.isEmpty(after.splitNames)) {
23085                for (int i = 0; i < after.splitNames.length; i++) {
23086                    final String splitName = after.splitNames[i];
23087                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23088                    if (j != -1) {
23089                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23090                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23091                                    "Update split " + splitName + " revision code "
23092                                    + after.splitRevisionCodes[i] + " is older than current "
23093                                    + before.splitRevisionCodes[j]);
23094                        }
23095                    }
23096                }
23097            }
23098        }
23099    }
23100
23101    private static class MoveCallbacks extends Handler {
23102        private static final int MSG_CREATED = 1;
23103        private static final int MSG_STATUS_CHANGED = 2;
23104
23105        private final RemoteCallbackList<IPackageMoveObserver>
23106                mCallbacks = new RemoteCallbackList<>();
23107
23108        private final SparseIntArray mLastStatus = new SparseIntArray();
23109
23110        public MoveCallbacks(Looper looper) {
23111            super(looper);
23112        }
23113
23114        public void register(IPackageMoveObserver callback) {
23115            mCallbacks.register(callback);
23116        }
23117
23118        public void unregister(IPackageMoveObserver callback) {
23119            mCallbacks.unregister(callback);
23120        }
23121
23122        @Override
23123        public void handleMessage(Message msg) {
23124            final SomeArgs args = (SomeArgs) msg.obj;
23125            final int n = mCallbacks.beginBroadcast();
23126            for (int i = 0; i < n; i++) {
23127                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23128                try {
23129                    invokeCallback(callback, msg.what, args);
23130                } catch (RemoteException ignored) {
23131                }
23132            }
23133            mCallbacks.finishBroadcast();
23134            args.recycle();
23135        }
23136
23137        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23138                throws RemoteException {
23139            switch (what) {
23140                case MSG_CREATED: {
23141                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23142                    break;
23143                }
23144                case MSG_STATUS_CHANGED: {
23145                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23146                    break;
23147                }
23148            }
23149        }
23150
23151        private void notifyCreated(int moveId, Bundle extras) {
23152            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23153
23154            final SomeArgs args = SomeArgs.obtain();
23155            args.argi1 = moveId;
23156            args.arg2 = extras;
23157            obtainMessage(MSG_CREATED, args).sendToTarget();
23158        }
23159
23160        private void notifyStatusChanged(int moveId, int status) {
23161            notifyStatusChanged(moveId, status, -1);
23162        }
23163
23164        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23165            Slog.v(TAG, "Move " + moveId + " status " + status);
23166
23167            final SomeArgs args = SomeArgs.obtain();
23168            args.argi1 = moveId;
23169            args.argi2 = status;
23170            args.arg3 = estMillis;
23171            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23172
23173            synchronized (mLastStatus) {
23174                mLastStatus.put(moveId, status);
23175            }
23176        }
23177    }
23178
23179    private final static class OnPermissionChangeListeners extends Handler {
23180        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23181
23182        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23183                new RemoteCallbackList<>();
23184
23185        public OnPermissionChangeListeners(Looper looper) {
23186            super(looper);
23187        }
23188
23189        @Override
23190        public void handleMessage(Message msg) {
23191            switch (msg.what) {
23192                case MSG_ON_PERMISSIONS_CHANGED: {
23193                    final int uid = msg.arg1;
23194                    handleOnPermissionsChanged(uid);
23195                } break;
23196            }
23197        }
23198
23199        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23200            mPermissionListeners.register(listener);
23201
23202        }
23203
23204        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23205            mPermissionListeners.unregister(listener);
23206        }
23207
23208        public void onPermissionsChanged(int uid) {
23209            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23210                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23211            }
23212        }
23213
23214        private void handleOnPermissionsChanged(int uid) {
23215            final int count = mPermissionListeners.beginBroadcast();
23216            try {
23217                for (int i = 0; i < count; i++) {
23218                    IOnPermissionsChangeListener callback = mPermissionListeners
23219                            .getBroadcastItem(i);
23220                    try {
23221                        callback.onPermissionsChanged(uid);
23222                    } catch (RemoteException e) {
23223                        Log.e(TAG, "Permission listener is dead", e);
23224                    }
23225                }
23226            } finally {
23227                mPermissionListeners.finishBroadcast();
23228            }
23229        }
23230    }
23231
23232    private class PackageManagerNative extends IPackageManagerNative.Stub {
23233        @Override
23234        public String[] getNamesForUids(int[] uids) throws RemoteException {
23235            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23236            // massage results so they can be parsed by the native binder
23237            for (int i = results.length - 1; i >= 0; --i) {
23238                if (results[i] == null) {
23239                    results[i] = "";
23240                }
23241            }
23242            return results;
23243        }
23244
23245        // NB: this differentiates between preloads and sideloads
23246        @Override
23247        public String getInstallerForPackage(String packageName) throws RemoteException {
23248            final String installerName = getInstallerPackageName(packageName);
23249            if (!TextUtils.isEmpty(installerName)) {
23250                return installerName;
23251            }
23252            // differentiate between preload and sideload
23253            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23254            ApplicationInfo appInfo = getApplicationInfo(packageName,
23255                                    /*flags*/ 0,
23256                                    /*userId*/ callingUser);
23257            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23258                return "preload";
23259            }
23260            return "";
23261        }
23262
23263        @Override
23264        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23265            try {
23266                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23267                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23268                if (pInfo != null) {
23269                    return pInfo.getLongVersionCode();
23270                }
23271            } catch (Exception e) {
23272            }
23273            return 0;
23274        }
23275    }
23276
23277    private class PackageManagerInternalImpl extends PackageManagerInternal {
23278        @Override
23279        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23280                int flagValues, int userId) {
23281            PackageManagerService.this.updatePermissionFlags(
23282                    permName, packageName, flagMask, flagValues, userId);
23283        }
23284
23285        @Override
23286        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23287            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23288        }
23289
23290        @Override
23291        public boolean isInstantApp(String packageName, int userId) {
23292            return PackageManagerService.this.isInstantApp(packageName, userId);
23293        }
23294
23295        @Override
23296        public String getInstantAppPackageName(int uid) {
23297            return PackageManagerService.this.getInstantAppPackageName(uid);
23298        }
23299
23300        @Override
23301        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23302            synchronized (mPackages) {
23303                return PackageManagerService.this.filterAppAccessLPr(
23304                        (PackageSetting) pkg.mExtras, callingUid, userId);
23305            }
23306        }
23307
23308        @Override
23309        public PackageParser.Package getPackage(String packageName) {
23310            synchronized (mPackages) {
23311                packageName = resolveInternalPackageNameLPr(
23312                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23313                return mPackages.get(packageName);
23314            }
23315        }
23316
23317        @Override
23318        public PackageList getPackageList(PackageListObserver observer) {
23319            synchronized (mPackages) {
23320                final int N = mPackages.size();
23321                final ArrayList<String> list = new ArrayList<>(N);
23322                for (int i = 0; i < N; i++) {
23323                    list.add(mPackages.keyAt(i));
23324                }
23325                final PackageList packageList = new PackageList(list, observer);
23326                if (observer != null) {
23327                    mPackageListObservers.add(packageList);
23328                }
23329                return packageList;
23330            }
23331        }
23332
23333        @Override
23334        public void removePackageListObserver(PackageListObserver observer) {
23335            synchronized (mPackages) {
23336                mPackageListObservers.remove(observer);
23337            }
23338        }
23339
23340        @Override
23341        public PackageParser.Package getDisabledPackage(String packageName) {
23342            synchronized (mPackages) {
23343                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23344                return (ps != null) ? ps.pkg : null;
23345            }
23346        }
23347
23348        @Override
23349        public String getKnownPackageName(int knownPackage, int userId) {
23350            switch(knownPackage) {
23351                case PackageManagerInternal.PACKAGE_BROWSER:
23352                    return getDefaultBrowserPackageName(userId);
23353                case PackageManagerInternal.PACKAGE_INSTALLER:
23354                    return mRequiredInstallerPackage;
23355                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23356                    return mSetupWizardPackage;
23357                case PackageManagerInternal.PACKAGE_SYSTEM:
23358                    return "android";
23359                case PackageManagerInternal.PACKAGE_VERIFIER:
23360                    return mRequiredVerifierPackage;
23361            }
23362            return null;
23363        }
23364
23365        @Override
23366        public boolean isResolveActivityComponent(ComponentInfo component) {
23367            return mResolveActivity.packageName.equals(component.packageName)
23368                    && mResolveActivity.name.equals(component.name);
23369        }
23370
23371        @Override
23372        public void setLocationPackagesProvider(PackagesProvider provider) {
23373            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23374        }
23375
23376        @Override
23377        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23378            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23379        }
23380
23381        @Override
23382        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23383            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23384        }
23385
23386        @Override
23387        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23388            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23389        }
23390
23391        @Override
23392        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23393            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23394        }
23395
23396        @Override
23397        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23398            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23399        }
23400
23401        @Override
23402        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23403            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23404        }
23405
23406        @Override
23407        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23408            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23409        }
23410
23411        @Override
23412        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23413            synchronized (mPackages) {
23414                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23415            }
23416            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23417        }
23418
23419        @Override
23420        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23421            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23422                    packageName, userId);
23423        }
23424
23425        @Override
23426        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23427            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23428                    packageName, userId);
23429        }
23430
23431        @Override
23432        public void setKeepUninstalledPackages(final List<String> packageList) {
23433            Preconditions.checkNotNull(packageList);
23434            List<String> removedFromList = null;
23435            synchronized (mPackages) {
23436                if (mKeepUninstalledPackages != null) {
23437                    final int packagesCount = mKeepUninstalledPackages.size();
23438                    for (int i = 0; i < packagesCount; i++) {
23439                        String oldPackage = mKeepUninstalledPackages.get(i);
23440                        if (packageList != null && packageList.contains(oldPackage)) {
23441                            continue;
23442                        }
23443                        if (removedFromList == null) {
23444                            removedFromList = new ArrayList<>();
23445                        }
23446                        removedFromList.add(oldPackage);
23447                    }
23448                }
23449                mKeepUninstalledPackages = new ArrayList<>(packageList);
23450                if (removedFromList != null) {
23451                    final int removedCount = removedFromList.size();
23452                    for (int i = 0; i < removedCount; i++) {
23453                        deletePackageIfUnusedLPr(removedFromList.get(i));
23454                    }
23455                }
23456            }
23457        }
23458
23459        @Override
23460        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23461            synchronized (mPackages) {
23462                return mPermissionManager.isPermissionsReviewRequired(
23463                        mPackages.get(packageName), userId);
23464            }
23465        }
23466
23467        @Override
23468        public PackageInfo getPackageInfo(
23469                String packageName, int flags, int filterCallingUid, int userId) {
23470            return PackageManagerService.this
23471                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23472                            flags, filterCallingUid, userId);
23473        }
23474
23475        @Override
23476        public int getPackageUid(String packageName, int flags, int userId) {
23477            return PackageManagerService.this
23478                    .getPackageUid(packageName, flags, userId);
23479        }
23480
23481        @Override
23482        public ApplicationInfo getApplicationInfo(
23483                String packageName, int flags, int filterCallingUid, int userId) {
23484            return PackageManagerService.this
23485                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23486        }
23487
23488        @Override
23489        public ActivityInfo getActivityInfo(
23490                ComponentName component, int flags, int filterCallingUid, int userId) {
23491            return PackageManagerService.this
23492                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23493        }
23494
23495        @Override
23496        public List<ResolveInfo> queryIntentActivities(
23497                Intent intent, int flags, int filterCallingUid, int userId) {
23498            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23499            return PackageManagerService.this
23500                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23501                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23502        }
23503
23504        @Override
23505        public List<ResolveInfo> queryIntentServices(
23506                Intent intent, int flags, int callingUid, int userId) {
23507            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23508            return PackageManagerService.this
23509                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23510                            false);
23511        }
23512
23513        @Override
23514        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23515                int userId) {
23516            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23517        }
23518
23519        @Override
23520        public void setDeviceAndProfileOwnerPackages(
23521                int deviceOwnerUserId, String deviceOwnerPackage,
23522                SparseArray<String> profileOwnerPackages) {
23523            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23524                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23525        }
23526
23527        @Override
23528        public boolean isPackageDataProtected(int userId, String packageName) {
23529            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23530        }
23531
23532        @Override
23533        public boolean isPackageEphemeral(int userId, String packageName) {
23534            synchronized (mPackages) {
23535                final PackageSetting ps = mSettings.mPackages.get(packageName);
23536                return ps != null ? ps.getInstantApp(userId) : false;
23537            }
23538        }
23539
23540        @Override
23541        public boolean wasPackageEverLaunched(String packageName, int userId) {
23542            synchronized (mPackages) {
23543                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23544            }
23545        }
23546
23547        @Override
23548        public void grantRuntimePermission(String packageName, String permName, int userId,
23549                boolean overridePolicy) {
23550            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23551                    permName, packageName, overridePolicy, getCallingUid(), userId,
23552                    mPermissionCallback);
23553        }
23554
23555        @Override
23556        public void revokeRuntimePermission(String packageName, String permName, int userId,
23557                boolean overridePolicy) {
23558            mPermissionManager.revokeRuntimePermission(
23559                    permName, packageName, overridePolicy, getCallingUid(), userId,
23560                    mPermissionCallback);
23561        }
23562
23563        @Override
23564        public String getNameForUid(int uid) {
23565            return PackageManagerService.this.getNameForUid(uid);
23566        }
23567
23568        @Override
23569        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23570                Intent origIntent, String resolvedType, String callingPackage,
23571                Bundle verificationBundle, int userId) {
23572            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23573                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23574                    userId);
23575        }
23576
23577        @Override
23578        public void grantEphemeralAccess(int userId, Intent intent,
23579                int targetAppId, int ephemeralAppId) {
23580            synchronized (mPackages) {
23581                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23582                        targetAppId, ephemeralAppId);
23583            }
23584        }
23585
23586        @Override
23587        public boolean isInstantAppInstallerComponent(ComponentName component) {
23588            synchronized (mPackages) {
23589                return mInstantAppInstallerActivity != null
23590                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23591            }
23592        }
23593
23594        @Override
23595        public void pruneInstantApps() {
23596            mInstantAppRegistry.pruneInstantApps();
23597        }
23598
23599        @Override
23600        public String getSetupWizardPackageName() {
23601            return mSetupWizardPackage;
23602        }
23603
23604        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23605            if (policy != null) {
23606                mExternalSourcesPolicy = policy;
23607            }
23608        }
23609
23610        @Override
23611        public boolean isPackagePersistent(String packageName) {
23612            synchronized (mPackages) {
23613                PackageParser.Package pkg = mPackages.get(packageName);
23614                return pkg != null
23615                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23616                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23617                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23618                        : false;
23619            }
23620        }
23621
23622        @Override
23623        public boolean isLegacySystemApp(Package pkg) {
23624            synchronized (mPackages) {
23625                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23626                return mPromoteSystemApps
23627                        && ps.isSystem()
23628                        && mExistingSystemPackages.contains(ps.name);
23629            }
23630        }
23631
23632        @Override
23633        public List<PackageInfo> getOverlayPackages(int userId) {
23634            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23635            synchronized (mPackages) {
23636                for (PackageParser.Package p : mPackages.values()) {
23637                    if (p.mOverlayTarget != null) {
23638                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23639                        if (pkg != null) {
23640                            overlayPackages.add(pkg);
23641                        }
23642                    }
23643                }
23644            }
23645            return overlayPackages;
23646        }
23647
23648        @Override
23649        public List<String> getTargetPackageNames(int userId) {
23650            List<String> targetPackages = new ArrayList<>();
23651            synchronized (mPackages) {
23652                for (PackageParser.Package p : mPackages.values()) {
23653                    if (p.mOverlayTarget == null) {
23654                        targetPackages.add(p.packageName);
23655                    }
23656                }
23657            }
23658            return targetPackages;
23659        }
23660
23661        @Override
23662        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23663                @Nullable List<String> overlayPackageNames) {
23664            synchronized (mPackages) {
23665                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23666                    Slog.e(TAG, "failed to find package " + targetPackageName);
23667                    return false;
23668                }
23669                ArrayList<String> overlayPaths = null;
23670                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23671                    final int N = overlayPackageNames.size();
23672                    overlayPaths = new ArrayList<>(N);
23673                    for (int i = 0; i < N; i++) {
23674                        final String packageName = overlayPackageNames.get(i);
23675                        final PackageParser.Package pkg = mPackages.get(packageName);
23676                        if (pkg == null) {
23677                            Slog.e(TAG, "failed to find package " + packageName);
23678                            return false;
23679                        }
23680                        overlayPaths.add(pkg.baseCodePath);
23681                    }
23682                }
23683
23684                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23685                ps.setOverlayPaths(overlayPaths, userId);
23686                return true;
23687            }
23688        }
23689
23690        @Override
23691        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23692                int flags, int userId, boolean resolveForStart) {
23693            return resolveIntentInternal(
23694                    intent, resolvedType, flags, userId, resolveForStart);
23695        }
23696
23697        @Override
23698        public ResolveInfo resolveService(Intent intent, String resolvedType,
23699                int flags, int userId, int callingUid) {
23700            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23701        }
23702
23703        @Override
23704        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23705            return PackageManagerService.this.resolveContentProviderInternal(
23706                    name, flags, userId);
23707        }
23708
23709        @Override
23710        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23711            synchronized (mPackages) {
23712                mIsolatedOwners.put(isolatedUid, ownerUid);
23713            }
23714        }
23715
23716        @Override
23717        public void removeIsolatedUid(int isolatedUid) {
23718            synchronized (mPackages) {
23719                mIsolatedOwners.delete(isolatedUid);
23720            }
23721        }
23722
23723        @Override
23724        public int getUidTargetSdkVersion(int uid) {
23725            synchronized (mPackages) {
23726                return getUidTargetSdkVersionLockedLPr(uid);
23727            }
23728        }
23729
23730        @Override
23731        public int getPackageTargetSdkVersion(String packageName) {
23732            synchronized (mPackages) {
23733                return getPackageTargetSdkVersionLockedLPr(packageName);
23734            }
23735        }
23736
23737        @Override
23738        public boolean canAccessInstantApps(int callingUid, int userId) {
23739            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23740        }
23741
23742        @Override
23743        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23744            synchronized (mPackages) {
23745                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23746            }
23747        }
23748
23749        @Override
23750        public void notifyPackageUse(String packageName, int reason) {
23751            synchronized (mPackages) {
23752                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23753            }
23754        }
23755    }
23756
23757    @Override
23758    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23759        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23760        synchronized (mPackages) {
23761            final long identity = Binder.clearCallingIdentity();
23762            try {
23763                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23764                        packageNames, userId);
23765            } finally {
23766                Binder.restoreCallingIdentity(identity);
23767            }
23768        }
23769    }
23770
23771    @Override
23772    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23773        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23774        synchronized (mPackages) {
23775            final long identity = Binder.clearCallingIdentity();
23776            try {
23777                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23778                        packageNames, userId);
23779            } finally {
23780                Binder.restoreCallingIdentity(identity);
23781            }
23782        }
23783    }
23784
23785    private static void enforceSystemOrPhoneCaller(String tag) {
23786        int callingUid = Binder.getCallingUid();
23787        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23788            throw new SecurityException(
23789                    "Cannot call " + tag + " from UID " + callingUid);
23790        }
23791    }
23792
23793    boolean isHistoricalPackageUsageAvailable() {
23794        return mPackageUsage.isHistoricalPackageUsageAvailable();
23795    }
23796
23797    /**
23798     * Return a <b>copy</b> of the collection of packages known to the package manager.
23799     * @return A copy of the values of mPackages.
23800     */
23801    Collection<PackageParser.Package> getPackages() {
23802        synchronized (mPackages) {
23803            return new ArrayList<>(mPackages.values());
23804        }
23805    }
23806
23807    /**
23808     * Logs process start information (including base APK hash) to the security log.
23809     * @hide
23810     */
23811    @Override
23812    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23813            String apkFile, int pid) {
23814        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23815            return;
23816        }
23817        if (!SecurityLog.isLoggingEnabled()) {
23818            return;
23819        }
23820        Bundle data = new Bundle();
23821        data.putLong("startTimestamp", System.currentTimeMillis());
23822        data.putString("processName", processName);
23823        data.putInt("uid", uid);
23824        data.putString("seinfo", seinfo);
23825        data.putString("apkFile", apkFile);
23826        data.putInt("pid", pid);
23827        Message msg = mProcessLoggingHandler.obtainMessage(
23828                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23829        msg.setData(data);
23830        mProcessLoggingHandler.sendMessage(msg);
23831    }
23832
23833    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23834        return mCompilerStats.getPackageStats(pkgName);
23835    }
23836
23837    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23838        return getOrCreateCompilerPackageStats(pkg.packageName);
23839    }
23840
23841    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23842        return mCompilerStats.getOrCreatePackageStats(pkgName);
23843    }
23844
23845    public void deleteCompilerPackageStats(String pkgName) {
23846        mCompilerStats.deletePackageStats(pkgName);
23847    }
23848
23849    @Override
23850    public int getInstallReason(String packageName, int userId) {
23851        final int callingUid = Binder.getCallingUid();
23852        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23853                true /* requireFullPermission */, false /* checkShell */,
23854                "get install reason");
23855        synchronized (mPackages) {
23856            final PackageSetting ps = mSettings.mPackages.get(packageName);
23857            if (filterAppAccessLPr(ps, callingUid, userId)) {
23858                return PackageManager.INSTALL_REASON_UNKNOWN;
23859            }
23860            if (ps != null) {
23861                return ps.getInstallReason(userId);
23862            }
23863        }
23864        return PackageManager.INSTALL_REASON_UNKNOWN;
23865    }
23866
23867    @Override
23868    public boolean canRequestPackageInstalls(String packageName, int userId) {
23869        return canRequestPackageInstallsInternal(packageName, 0, userId,
23870                true /* throwIfPermNotDeclared*/);
23871    }
23872
23873    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23874            boolean throwIfPermNotDeclared) {
23875        int callingUid = Binder.getCallingUid();
23876        int uid = getPackageUid(packageName, 0, userId);
23877        if (callingUid != uid && callingUid != Process.ROOT_UID
23878                && callingUid != Process.SYSTEM_UID) {
23879            throw new SecurityException(
23880                    "Caller uid " + callingUid + " does not own package " + packageName);
23881        }
23882        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23883        if (info == null) {
23884            return false;
23885        }
23886        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23887            return false;
23888        }
23889        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23890        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23891        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23892            if (throwIfPermNotDeclared) {
23893                throw new SecurityException("Need to declare " + appOpPermission
23894                        + " to call this api");
23895            } else {
23896                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23897                return false;
23898            }
23899        }
23900        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23901            return false;
23902        }
23903        if (mExternalSourcesPolicy != null) {
23904            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23905            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23906                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23907            }
23908        }
23909        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23910    }
23911
23912    @Override
23913    public ComponentName getInstantAppResolverSettingsComponent() {
23914        return mInstantAppResolverSettingsComponent;
23915    }
23916
23917    @Override
23918    public ComponentName getInstantAppInstallerComponent() {
23919        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23920            return null;
23921        }
23922        return mInstantAppInstallerActivity == null
23923                ? null : mInstantAppInstallerActivity.getComponentName();
23924    }
23925
23926    @Override
23927    public String getInstantAppAndroidId(String packageName, int userId) {
23928        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23929                "getInstantAppAndroidId");
23930        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23931                true /* requireFullPermission */, false /* checkShell */,
23932                "getInstantAppAndroidId");
23933        // Make sure the target is an Instant App.
23934        if (!isInstantApp(packageName, userId)) {
23935            return null;
23936        }
23937        synchronized (mPackages) {
23938            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23939        }
23940    }
23941
23942    boolean canHaveOatDir(String packageName) {
23943        synchronized (mPackages) {
23944            PackageParser.Package p = mPackages.get(packageName);
23945            if (p == null) {
23946                return false;
23947            }
23948            return p.canHaveOatDir();
23949        }
23950    }
23951
23952    private String getOatDir(PackageParser.Package pkg) {
23953        if (!pkg.canHaveOatDir()) {
23954            return null;
23955        }
23956        File codePath = new File(pkg.codePath);
23957        if (codePath.isDirectory()) {
23958            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23959        }
23960        return null;
23961    }
23962
23963    void deleteOatArtifactsOfPackage(String packageName) {
23964        final String[] instructionSets;
23965        final List<String> codePaths;
23966        final String oatDir;
23967        final PackageParser.Package pkg;
23968        synchronized (mPackages) {
23969            pkg = mPackages.get(packageName);
23970        }
23971        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
23972        codePaths = pkg.getAllCodePaths();
23973        oatDir = getOatDir(pkg);
23974
23975        for (String codePath : codePaths) {
23976            for (String isa : instructionSets) {
23977                try {
23978                    mInstaller.deleteOdex(codePath, isa, oatDir);
23979                } catch (InstallerException e) {
23980                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
23981                }
23982            }
23983        }
23984    }
23985
23986    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
23987        Set<String> unusedPackages = new HashSet<>();
23988        long currentTimeInMillis = System.currentTimeMillis();
23989        synchronized (mPackages) {
23990            for (PackageParser.Package pkg : mPackages.values()) {
23991                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
23992                if (ps == null) {
23993                    continue;
23994                }
23995                PackageDexUsage.PackageUseInfo packageUseInfo =
23996                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
23997                if (PackageManagerServiceUtils
23998                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
23999                                downgradeTimeThresholdMillis, packageUseInfo,
24000                                pkg.getLatestPackageUseTimeInMills(),
24001                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24002                    unusedPackages.add(pkg.packageName);
24003                }
24004            }
24005        }
24006        return unusedPackages;
24007    }
24008
24009    @Override
24010    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24011            int userId) {
24012        final int callingUid = Binder.getCallingUid();
24013        final int callingAppId = UserHandle.getAppId(callingUid);
24014
24015        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24016                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24017
24018        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24019                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24020            throw new SecurityException("Caller must have the "
24021                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24022        }
24023
24024        synchronized(mPackages) {
24025            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24026            scheduleWritePackageRestrictionsLocked(userId);
24027        }
24028    }
24029
24030    @Nullable
24031    @Override
24032    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24033        final int callingUid = Binder.getCallingUid();
24034        final int callingAppId = UserHandle.getAppId(callingUid);
24035
24036        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24037                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24038
24039        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24040                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24041            throw new SecurityException("Caller must have the "
24042                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24043        }
24044
24045        synchronized(mPackages) {
24046            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24047        }
24048    }
24049}
24050
24051interface PackageSender {
24052    /**
24053     * @param userIds User IDs where the action occurred on a full application
24054     * @param instantUserIds User IDs where the action occurred on an instant application
24055     */
24056    void sendPackageBroadcast(final String action, final String pkg,
24057        final Bundle extras, final int flags, final String targetPkg,
24058        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24059    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24060        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24061    void notifyPackageAdded(String packageName);
24062    void notifyPackageRemoved(String packageName);
24063}
24064