PackageManagerService.java revision e09bcb4b86dacdf89cba218bd075c5f4c4ffb5a5
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 mWebInstantAppsDisabled;
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 areWebInstantAppsDisabled() {
5954        return mWebInstantAppsDisabled;
5955    }
5956
5957    private boolean isInstantAppResolutionAllowed(
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 {
5983            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
5984                return false;
5985            } else if (areWebInstantAppsDisabled()) {
5986                return false;
5987            }
5988        }
5989        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5990        // Or if there's already an ephemeral app installed that handles the action
5991        synchronized (mPackages) {
5992            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5993            for (int n = 0; n < count; n++) {
5994                final ResolveInfo info = resolvedActivities.get(n);
5995                final String packageName = info.activityInfo.packageName;
5996                final PackageSetting ps = mSettings.mPackages.get(packageName);
5997                if (ps != null) {
5998                    // only check domain verification status if the app is not a browser
5999                    if (!info.handleAllWebDataURI) {
6000                        // Try to get the status from User settings first
6001                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6002                        final int status = (int) (packedStatus >> 32);
6003                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6004                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6005                            if (DEBUG_INSTANT) {
6006                                Slog.v(TAG, "DENY instant app;"
6007                                    + " pkg: " + packageName + ", status: " + status);
6008                            }
6009                            return false;
6010                        }
6011                    }
6012                    if (ps.getInstantApp(userId)) {
6013                        if (DEBUG_INSTANT) {
6014                            Slog.v(TAG, "DENY instant app installed;"
6015                                    + " pkg: " + packageName);
6016                        }
6017                        return false;
6018                    }
6019                }
6020            }
6021        }
6022        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6023        return true;
6024    }
6025
6026    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6027            Intent origIntent, String resolvedType, String callingPackage,
6028            Bundle verificationBundle, int userId) {
6029        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6030                new InstantAppRequest(responseObj, origIntent, resolvedType,
6031                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6032        mHandler.sendMessage(msg);
6033    }
6034
6035    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6036            int flags, List<ResolveInfo> query, int userId) {
6037        if (query != null) {
6038            final int N = query.size();
6039            if (N == 1) {
6040                return query.get(0);
6041            } else if (N > 1) {
6042                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6043                // If there is more than one activity with the same priority,
6044                // then let the user decide between them.
6045                ResolveInfo r0 = query.get(0);
6046                ResolveInfo r1 = query.get(1);
6047                if (DEBUG_INTENT_MATCHING || debug) {
6048                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6049                            + r1.activityInfo.name + "=" + r1.priority);
6050                }
6051                // If the first activity has a higher priority, or a different
6052                // default, then it is always desirable to pick it.
6053                if (r0.priority != r1.priority
6054                        || r0.preferredOrder != r1.preferredOrder
6055                        || r0.isDefault != r1.isDefault) {
6056                    return query.get(0);
6057                }
6058                // If we have saved a preference for a preferred activity for
6059                // this Intent, use that.
6060                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6061                        flags, query, r0.priority, true, false, debug, userId);
6062                if (ri != null) {
6063                    return ri;
6064                }
6065                // If we have an ephemeral app, use it
6066                for (int i = 0; i < N; i++) {
6067                    ri = query.get(i);
6068                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6069                        final String packageName = ri.activityInfo.packageName;
6070                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6071                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6072                        final int status = (int)(packedStatus >> 32);
6073                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6074                            return ri;
6075                        }
6076                    }
6077                }
6078                ri = new ResolveInfo(mResolveInfo);
6079                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6080                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6081                // If all of the options come from the same package, show the application's
6082                // label and icon instead of the generic resolver's.
6083                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6084                // and then throw away the ResolveInfo itself, meaning that the caller loses
6085                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6086                // a fallback for this case; we only set the target package's resources on
6087                // the ResolveInfo, not the ActivityInfo.
6088                final String intentPackage = intent.getPackage();
6089                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6090                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6091                    ri.resolvePackageName = intentPackage;
6092                    if (userNeedsBadging(userId)) {
6093                        ri.noResourceId = true;
6094                    } else {
6095                        ri.icon = appi.icon;
6096                    }
6097                    ri.iconResourceId = appi.icon;
6098                    ri.labelRes = appi.labelRes;
6099                }
6100                ri.activityInfo.applicationInfo = new ApplicationInfo(
6101                        ri.activityInfo.applicationInfo);
6102                if (userId != 0) {
6103                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6104                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6105                }
6106                // Make sure that the resolver is displayable in car mode
6107                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6108                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6109                return ri;
6110            }
6111        }
6112        return null;
6113    }
6114
6115    /**
6116     * Return true if the given list is not empty and all of its contents have
6117     * an activityInfo with the given package name.
6118     */
6119    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6120        if (ArrayUtils.isEmpty(list)) {
6121            return false;
6122        }
6123        for (int i = 0, N = list.size(); i < N; i++) {
6124            final ResolveInfo ri = list.get(i);
6125            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6126            if (ai == null || !packageName.equals(ai.packageName)) {
6127                return false;
6128            }
6129        }
6130        return true;
6131    }
6132
6133    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6134            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6135        final int N = query.size();
6136        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6137                .get(userId);
6138        // Get the list of persistent preferred activities that handle the intent
6139        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6140        List<PersistentPreferredActivity> pprefs = ppir != null
6141                ? ppir.queryIntent(intent, resolvedType,
6142                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6143                        userId)
6144                : null;
6145        if (pprefs != null && pprefs.size() > 0) {
6146            final int M = pprefs.size();
6147            for (int i=0; i<M; i++) {
6148                final PersistentPreferredActivity ppa = pprefs.get(i);
6149                if (DEBUG_PREFERRED || debug) {
6150                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6151                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6152                            + "\n  component=" + ppa.mComponent);
6153                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6154                }
6155                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6156                        flags | MATCH_DISABLED_COMPONENTS, userId);
6157                if (DEBUG_PREFERRED || debug) {
6158                    Slog.v(TAG, "Found persistent preferred activity:");
6159                    if (ai != null) {
6160                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6161                    } else {
6162                        Slog.v(TAG, "  null");
6163                    }
6164                }
6165                if (ai == null) {
6166                    // This previously registered persistent preferred activity
6167                    // component is no longer known. Ignore it and do NOT remove it.
6168                    continue;
6169                }
6170                for (int j=0; j<N; j++) {
6171                    final ResolveInfo ri = query.get(j);
6172                    if (!ri.activityInfo.applicationInfo.packageName
6173                            .equals(ai.applicationInfo.packageName)) {
6174                        continue;
6175                    }
6176                    if (!ri.activityInfo.name.equals(ai.name)) {
6177                        continue;
6178                    }
6179                    //  Found a persistent preference that can handle the intent.
6180                    if (DEBUG_PREFERRED || debug) {
6181                        Slog.v(TAG, "Returning persistent preferred activity: " +
6182                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6183                    }
6184                    return ri;
6185                }
6186            }
6187        }
6188        return null;
6189    }
6190
6191    // TODO: handle preferred activities missing while user has amnesia
6192    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6193            List<ResolveInfo> query, int priority, boolean always,
6194            boolean removeMatches, boolean debug, int userId) {
6195        if (!sUserManager.exists(userId)) return null;
6196        final int callingUid = Binder.getCallingUid();
6197        flags = updateFlagsForResolve(
6198                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6199        intent = updateIntentForResolve(intent);
6200        // writer
6201        synchronized (mPackages) {
6202            // Try to find a matching persistent preferred activity.
6203            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6204                    debug, userId);
6205
6206            // If a persistent preferred activity matched, use it.
6207            if (pri != null) {
6208                return pri;
6209            }
6210
6211            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6212            // Get the list of preferred activities that handle the intent
6213            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6214            List<PreferredActivity> prefs = pir != null
6215                    ? pir.queryIntent(intent, resolvedType,
6216                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6217                            userId)
6218                    : null;
6219            if (prefs != null && prefs.size() > 0) {
6220                boolean changed = false;
6221                try {
6222                    // First figure out how good the original match set is.
6223                    // We will only allow preferred activities that came
6224                    // from the same match quality.
6225                    int match = 0;
6226
6227                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6228
6229                    final int N = query.size();
6230                    for (int j=0; j<N; j++) {
6231                        final ResolveInfo ri = query.get(j);
6232                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6233                                + ": 0x" + Integer.toHexString(match));
6234                        if (ri.match > match) {
6235                            match = ri.match;
6236                        }
6237                    }
6238
6239                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6240                            + Integer.toHexString(match));
6241
6242                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6243                    final int M = prefs.size();
6244                    for (int i=0; i<M; i++) {
6245                        final PreferredActivity pa = prefs.get(i);
6246                        if (DEBUG_PREFERRED || debug) {
6247                            Slog.v(TAG, "Checking PreferredActivity ds="
6248                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6249                                    + "\n  component=" + pa.mPref.mComponent);
6250                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6251                        }
6252                        if (pa.mPref.mMatch != match) {
6253                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6254                                    + Integer.toHexString(pa.mPref.mMatch));
6255                            continue;
6256                        }
6257                        // If it's not an "always" type preferred activity and that's what we're
6258                        // looking for, skip it.
6259                        if (always && !pa.mPref.mAlways) {
6260                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6261                            continue;
6262                        }
6263                        final ActivityInfo ai = getActivityInfo(
6264                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6265                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6266                                userId);
6267                        if (DEBUG_PREFERRED || debug) {
6268                            Slog.v(TAG, "Found preferred activity:");
6269                            if (ai != null) {
6270                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6271                            } else {
6272                                Slog.v(TAG, "  null");
6273                            }
6274                        }
6275                        if (ai == null) {
6276                            // This previously registered preferred activity
6277                            // component is no longer known.  Most likely an update
6278                            // to the app was installed and in the new version this
6279                            // component no longer exists.  Clean it up by removing
6280                            // it from the preferred activities list, and skip it.
6281                            Slog.w(TAG, "Removing dangling preferred activity: "
6282                                    + pa.mPref.mComponent);
6283                            pir.removeFilter(pa);
6284                            changed = true;
6285                            continue;
6286                        }
6287                        for (int j=0; j<N; j++) {
6288                            final ResolveInfo ri = query.get(j);
6289                            if (!ri.activityInfo.applicationInfo.packageName
6290                                    .equals(ai.applicationInfo.packageName)) {
6291                                continue;
6292                            }
6293                            if (!ri.activityInfo.name.equals(ai.name)) {
6294                                continue;
6295                            }
6296
6297                            if (removeMatches) {
6298                                pir.removeFilter(pa);
6299                                changed = true;
6300                                if (DEBUG_PREFERRED) {
6301                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6302                                }
6303                                break;
6304                            }
6305
6306                            // Okay we found a previously set preferred or last chosen app.
6307                            // If the result set is different from when this
6308                            // was created, and is not a subset of the preferred set, we need to
6309                            // clear it and re-ask the user their preference, if we're looking for
6310                            // an "always" type entry.
6311                            if (always && !pa.mPref.sameSet(query)) {
6312                                if (pa.mPref.isSuperset(query)) {
6313                                    // some components of the set are no longer present in
6314                                    // the query, but the preferred activity can still be reused
6315                                    if (DEBUG_PREFERRED) {
6316                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6317                                                + " still valid as only non-preferred components"
6318                                                + " were removed for " + intent + " type "
6319                                                + resolvedType);
6320                                    }
6321                                    // remove obsolete components and re-add the up-to-date filter
6322                                    PreferredActivity freshPa = new PreferredActivity(pa,
6323                                            pa.mPref.mMatch,
6324                                            pa.mPref.discardObsoleteComponents(query),
6325                                            pa.mPref.mComponent,
6326                                            pa.mPref.mAlways);
6327                                    pir.removeFilter(pa);
6328                                    pir.addFilter(freshPa);
6329                                    changed = true;
6330                                } else {
6331                                    Slog.i(TAG,
6332                                            "Result set changed, dropping preferred activity for "
6333                                                    + intent + " type " + resolvedType);
6334                                    if (DEBUG_PREFERRED) {
6335                                        Slog.v(TAG, "Removing preferred activity since set changed "
6336                                                + pa.mPref.mComponent);
6337                                    }
6338                                    pir.removeFilter(pa);
6339                                    // Re-add the filter as a "last chosen" entry (!always)
6340                                    PreferredActivity lastChosen = new PreferredActivity(
6341                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6342                                    pir.addFilter(lastChosen);
6343                                    changed = true;
6344                                    return null;
6345                                }
6346                            }
6347
6348                            // Yay! Either the set matched or we're looking for the last chosen
6349                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6350                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6351                            return ri;
6352                        }
6353                    }
6354                } finally {
6355                    if (changed) {
6356                        if (DEBUG_PREFERRED) {
6357                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6358                        }
6359                        scheduleWritePackageRestrictionsLocked(userId);
6360                    }
6361                }
6362            }
6363        }
6364        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6365        return null;
6366    }
6367
6368    /*
6369     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6370     */
6371    @Override
6372    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6373            int targetUserId) {
6374        mContext.enforceCallingOrSelfPermission(
6375                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6376        List<CrossProfileIntentFilter> matches =
6377                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6378        if (matches != null) {
6379            int size = matches.size();
6380            for (int i = 0; i < size; i++) {
6381                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6382            }
6383        }
6384        if (intent.hasWebURI()) {
6385            // cross-profile app linking works only towards the parent.
6386            final int callingUid = Binder.getCallingUid();
6387            final UserInfo parent = getProfileParent(sourceUserId);
6388            synchronized(mPackages) {
6389                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6390                        false /*includeInstantApps*/);
6391                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6392                        intent, resolvedType, flags, sourceUserId, parent.id);
6393                return xpDomainInfo != null;
6394            }
6395        }
6396        return false;
6397    }
6398
6399    private UserInfo getProfileParent(int userId) {
6400        final long identity = Binder.clearCallingIdentity();
6401        try {
6402            return sUserManager.getProfileParent(userId);
6403        } finally {
6404            Binder.restoreCallingIdentity(identity);
6405        }
6406    }
6407
6408    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6409            String resolvedType, int userId) {
6410        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6411        if (resolver != null) {
6412            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6413        }
6414        return null;
6415    }
6416
6417    @Override
6418    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6419            String resolvedType, int flags, int userId) {
6420        try {
6421            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6422
6423            return new ParceledListSlice<>(
6424                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6425        } finally {
6426            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6427        }
6428    }
6429
6430    /**
6431     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6432     * instant, returns {@code null}.
6433     */
6434    private String getInstantAppPackageName(int callingUid) {
6435        synchronized (mPackages) {
6436            // If the caller is an isolated app use the owner's uid for the lookup.
6437            if (Process.isIsolated(callingUid)) {
6438                callingUid = mIsolatedOwners.get(callingUid);
6439            }
6440            final int appId = UserHandle.getAppId(callingUid);
6441            final Object obj = mSettings.getUserIdLPr(appId);
6442            if (obj instanceof PackageSetting) {
6443                final PackageSetting ps = (PackageSetting) obj;
6444                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6445                return isInstantApp ? ps.pkg.packageName : null;
6446            }
6447        }
6448        return null;
6449    }
6450
6451    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6452            String resolvedType, int flags, int userId) {
6453        return queryIntentActivitiesInternal(
6454                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6455                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6456    }
6457
6458    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6459            String resolvedType, int flags, int filterCallingUid, int userId,
6460            boolean resolveForStart, boolean allowDynamicSplits) {
6461        if (!sUserManager.exists(userId)) return Collections.emptyList();
6462        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6463        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6464                false /* requireFullPermission */, false /* checkShell */,
6465                "query intent activities");
6466        final String pkgName = intent.getPackage();
6467        ComponentName comp = intent.getComponent();
6468        if (comp == null) {
6469            if (intent.getSelector() != null) {
6470                intent = intent.getSelector();
6471                comp = intent.getComponent();
6472            }
6473        }
6474
6475        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6476                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6477        if (comp != null) {
6478            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6479            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6480            if (ai != null) {
6481                // When specifying an explicit component, we prevent the activity from being
6482                // used when either 1) the calling package is normal and the activity is within
6483                // an ephemeral application or 2) the calling package is ephemeral and the
6484                // activity is not visible to ephemeral applications.
6485                final boolean matchInstantApp =
6486                        (flags & PackageManager.MATCH_INSTANT) != 0;
6487                final boolean matchVisibleToInstantAppOnly =
6488                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6489                final boolean matchExplicitlyVisibleOnly =
6490                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6491                final boolean isCallerInstantApp =
6492                        instantAppPkgName != null;
6493                final boolean isTargetSameInstantApp =
6494                        comp.getPackageName().equals(instantAppPkgName);
6495                final boolean isTargetInstantApp =
6496                        (ai.applicationInfo.privateFlags
6497                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6498                final boolean isTargetVisibleToInstantApp =
6499                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6500                final boolean isTargetExplicitlyVisibleToInstantApp =
6501                        isTargetVisibleToInstantApp
6502                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6503                final boolean isTargetHiddenFromInstantApp =
6504                        !isTargetVisibleToInstantApp
6505                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6506                final boolean blockResolution =
6507                        !isTargetSameInstantApp
6508                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6509                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6510                                        && isTargetHiddenFromInstantApp));
6511                if (!blockResolution) {
6512                    final ResolveInfo ri = new ResolveInfo();
6513                    ri.activityInfo = ai;
6514                    list.add(ri);
6515                }
6516            }
6517            return applyPostResolutionFilter(
6518                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6519        }
6520
6521        // reader
6522        boolean sortResult = false;
6523        boolean addInstant = false;
6524        List<ResolveInfo> result;
6525        synchronized (mPackages) {
6526            if (pkgName == null) {
6527                List<CrossProfileIntentFilter> matchingFilters =
6528                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6529                // Check for results that need to skip the current profile.
6530                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6531                        resolvedType, flags, userId);
6532                if (xpResolveInfo != null) {
6533                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6534                    xpResult.add(xpResolveInfo);
6535                    return applyPostResolutionFilter(
6536                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6537                            allowDynamicSplits, filterCallingUid, userId, intent);
6538                }
6539
6540                // Check for results in the current profile.
6541                result = filterIfNotSystemUser(mActivities.queryIntent(
6542                        intent, resolvedType, flags, userId), userId);
6543                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6544                        false /*skipPackageCheck*/);
6545                // Check for cross profile results.
6546                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6547                xpResolveInfo = queryCrossProfileIntents(
6548                        matchingFilters, intent, resolvedType, flags, userId,
6549                        hasNonNegativePriorityResult);
6550                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6551                    boolean isVisibleToUser = filterIfNotSystemUser(
6552                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6553                    if (isVisibleToUser) {
6554                        result.add(xpResolveInfo);
6555                        sortResult = true;
6556                    }
6557                }
6558                if (intent.hasWebURI()) {
6559                    CrossProfileDomainInfo xpDomainInfo = null;
6560                    final UserInfo parent = getProfileParent(userId);
6561                    if (parent != null) {
6562                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6563                                flags, userId, parent.id);
6564                    }
6565                    if (xpDomainInfo != null) {
6566                        if (xpResolveInfo != null) {
6567                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6568                            // in the result.
6569                            result.remove(xpResolveInfo);
6570                        }
6571                        if (result.size() == 0 && !addInstant) {
6572                            // No result in current profile, but found candidate in parent user.
6573                            // And we are not going to add emphemeral app, so we can return the
6574                            // result straight away.
6575                            result.add(xpDomainInfo.resolveInfo);
6576                            return applyPostResolutionFilter(result, instantAppPkgName,
6577                                    allowDynamicSplits, filterCallingUid, userId, intent);
6578                        }
6579                    } else if (result.size() <= 1 && !addInstant) {
6580                        // No result in parent user and <= 1 result in current profile, and we
6581                        // are not going to add emphemeral app, so we can return the result without
6582                        // further processing.
6583                        return applyPostResolutionFilter(result, instantAppPkgName,
6584                                allowDynamicSplits, filterCallingUid, userId, intent);
6585                    }
6586                    // We have more than one candidate (combining results from current and parent
6587                    // profile), so we need filtering and sorting.
6588                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6589                            intent, flags, result, xpDomainInfo, userId);
6590                    sortResult = true;
6591                }
6592            } else {
6593                final PackageParser.Package pkg = mPackages.get(pkgName);
6594                result = null;
6595                if (pkg != null) {
6596                    result = filterIfNotSystemUser(
6597                            mActivities.queryIntentForPackage(
6598                                    intent, resolvedType, flags, pkg.activities, userId),
6599                            userId);
6600                }
6601                if (result == null || result.size() == 0) {
6602                    // the caller wants to resolve for a particular package; however, there
6603                    // were no installed results, so, try to find an ephemeral result
6604                    addInstant = isInstantAppResolutionAllowed(
6605                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6606                    if (result == null) {
6607                        result = new ArrayList<>();
6608                    }
6609                }
6610            }
6611        }
6612        if (addInstant) {
6613            result = maybeAddInstantAppInstaller(
6614                    result, intent, resolvedType, flags, userId, resolveForStart);
6615        }
6616        if (sortResult) {
6617            Collections.sort(result, mResolvePrioritySorter);
6618        }
6619        return applyPostResolutionFilter(
6620                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6621    }
6622
6623    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6624            String resolvedType, int flags, int userId, boolean resolveForStart) {
6625        // first, check to see if we've got an instant app already installed
6626        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6627        ResolveInfo localInstantApp = null;
6628        boolean blockResolution = false;
6629        if (!alreadyResolvedLocally) {
6630            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6631                    flags
6632                        | PackageManager.GET_RESOLVED_FILTER
6633                        | PackageManager.MATCH_INSTANT
6634                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6635                    userId);
6636            for (int i = instantApps.size() - 1; i >= 0; --i) {
6637                final ResolveInfo info = instantApps.get(i);
6638                final String packageName = info.activityInfo.packageName;
6639                final PackageSetting ps = mSettings.mPackages.get(packageName);
6640                if (ps.getInstantApp(userId)) {
6641                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6642                    final int status = (int)(packedStatus >> 32);
6643                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6644                        // there's a local instant application installed, but, the user has
6645                        // chosen to never use it; skip resolution and don't acknowledge
6646                        // an instant application is even available
6647                        if (DEBUG_INSTANT) {
6648                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6649                        }
6650                        blockResolution = true;
6651                        break;
6652                    } else {
6653                        // we have a locally installed instant application; skip resolution
6654                        // but acknowledge there's an instant application available
6655                        if (DEBUG_INSTANT) {
6656                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6657                        }
6658                        localInstantApp = info;
6659                        break;
6660                    }
6661                }
6662            }
6663        }
6664        // no app installed, let's see if one's available
6665        AuxiliaryResolveInfo auxiliaryResponse = null;
6666        if (!blockResolution) {
6667            if (localInstantApp == null) {
6668                // we don't have an instant app locally, resolve externally
6669                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6670                final InstantAppRequest requestObject = new InstantAppRequest(
6671                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6672                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6673                        resolveForStart);
6674                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6675                        mInstantAppResolverConnection, requestObject);
6676                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6677            } else {
6678                // we have an instant application locally, but, we can't admit that since
6679                // callers shouldn't be able to determine prior browsing. create a dummy
6680                // auxiliary response so the downstream code behaves as if there's an
6681                // instant application available externally. when it comes time to start
6682                // the instant application, we'll do the right thing.
6683                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6684                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6685                                        ai.packageName, ai.versionCode, null /* splitName */);
6686            }
6687        }
6688        if (intent.isWebIntent() && auxiliaryResponse == null) {
6689            return result;
6690        }
6691        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6692        if (ps == null) {
6693            return result;
6694        }
6695        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6696        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6697                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6698        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6699                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6700        // add a non-generic filter
6701        ephemeralInstaller.filter = new IntentFilter();
6702        if (intent.getAction() != null) {
6703            ephemeralInstaller.filter.addAction(intent.getAction());
6704        }
6705        if (intent.getData() != null && intent.getData().getPath() != null) {
6706            ephemeralInstaller.filter.addDataPath(
6707                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6708        }
6709        ephemeralInstaller.isInstantAppAvailable = true;
6710        // make sure this resolver is the default
6711        ephemeralInstaller.isDefault = true;
6712        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6713        if (DEBUG_INSTANT) {
6714            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6715        }
6716
6717        result.add(ephemeralInstaller);
6718        return result;
6719    }
6720
6721    private static class CrossProfileDomainInfo {
6722        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6723        ResolveInfo resolveInfo;
6724        /* Best domain verification status of the activities found in the other profile */
6725        int bestDomainVerificationStatus;
6726    }
6727
6728    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6729            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6730        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6731                sourceUserId)) {
6732            return null;
6733        }
6734        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6735                resolvedType, flags, parentUserId);
6736
6737        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6738            return null;
6739        }
6740        CrossProfileDomainInfo result = null;
6741        int size = resultTargetUser.size();
6742        for (int i = 0; i < size; i++) {
6743            ResolveInfo riTargetUser = resultTargetUser.get(i);
6744            // Intent filter verification is only for filters that specify a host. So don't return
6745            // those that handle all web uris.
6746            if (riTargetUser.handleAllWebDataURI) {
6747                continue;
6748            }
6749            String packageName = riTargetUser.activityInfo.packageName;
6750            PackageSetting ps = mSettings.mPackages.get(packageName);
6751            if (ps == null) {
6752                continue;
6753            }
6754            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6755            int status = (int)(verificationState >> 32);
6756            if (result == null) {
6757                result = new CrossProfileDomainInfo();
6758                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6759                        sourceUserId, parentUserId);
6760                result.bestDomainVerificationStatus = status;
6761            } else {
6762                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6763                        result.bestDomainVerificationStatus);
6764            }
6765        }
6766        // Don't consider matches with status NEVER across profiles.
6767        if (result != null && result.bestDomainVerificationStatus
6768                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6769            return null;
6770        }
6771        return result;
6772    }
6773
6774    /**
6775     * Verification statuses are ordered from the worse to the best, except for
6776     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6777     */
6778    private int bestDomainVerificationStatus(int status1, int status2) {
6779        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6780            return status2;
6781        }
6782        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6783            return status1;
6784        }
6785        return (int) MathUtils.max(status1, status2);
6786    }
6787
6788    private boolean isUserEnabled(int userId) {
6789        long callingId = Binder.clearCallingIdentity();
6790        try {
6791            UserInfo userInfo = sUserManager.getUserInfo(userId);
6792            return userInfo != null && userInfo.isEnabled();
6793        } finally {
6794            Binder.restoreCallingIdentity(callingId);
6795        }
6796    }
6797
6798    /**
6799     * Filter out activities with systemUserOnly flag set, when current user is not System.
6800     *
6801     * @return filtered list
6802     */
6803    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6804        if (userId == UserHandle.USER_SYSTEM) {
6805            return resolveInfos;
6806        }
6807        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6808            ResolveInfo info = resolveInfos.get(i);
6809            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6810                resolveInfos.remove(i);
6811            }
6812        }
6813        return resolveInfos;
6814    }
6815
6816    /**
6817     * Filters out ephemeral activities.
6818     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6819     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6820     *
6821     * @param resolveInfos The pre-filtered list of resolved activities
6822     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6823     *          is performed.
6824     * @param intent
6825     * @return A filtered list of resolved activities.
6826     */
6827    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6828            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6829            Intent intent) {
6830        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6831        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6832            final ResolveInfo info = resolveInfos.get(i);
6833            // remove locally resolved instant app web results when disabled
6834            if (info.isInstantAppAvailable && blockInstant) {
6835                resolveInfos.remove(i);
6836                continue;
6837            }
6838            // allow activities that are defined in the provided package
6839            if (allowDynamicSplits
6840                    && info.activityInfo != null
6841                    && info.activityInfo.splitName != null
6842                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6843                            info.activityInfo.splitName)) {
6844                if (mInstantAppInstallerActivity == null) {
6845                    if (DEBUG_INSTALL) {
6846                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6847                    }
6848                    resolveInfos.remove(i);
6849                    continue;
6850                }
6851                // requested activity is defined in a split that hasn't been installed yet.
6852                // add the installer to the resolve list
6853                if (DEBUG_INSTALL) {
6854                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6855                }
6856                final ResolveInfo installerInfo = new ResolveInfo(
6857                        mInstantAppInstallerInfo);
6858                final ComponentName installFailureActivity = findInstallFailureActivity(
6859                        info.activityInfo.packageName,  filterCallingUid, userId);
6860                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6861                        installFailureActivity,
6862                        info.activityInfo.packageName,
6863                        info.activityInfo.applicationInfo.versionCode,
6864                        info.activityInfo.splitName);
6865                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6866                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6867                // add a non-generic filter
6868                installerInfo.filter = new IntentFilter();
6869
6870                // This resolve info may appear in the chooser UI, so let us make it
6871                // look as the one it replaces as far as the user is concerned which
6872                // requires loading the correct label and icon for the resolve info.
6873                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6874                installerInfo.labelRes = info.resolveLabelResId();
6875                installerInfo.icon = info.resolveIconResId();
6876
6877                // propagate priority/preferred order/default
6878                installerInfo.priority = info.priority;
6879                installerInfo.preferredOrder = info.preferredOrder;
6880                installerInfo.isDefault = info.isDefault;
6881                installerInfo.isInstantAppAvailable = true;
6882                resolveInfos.set(i, installerInfo);
6883                continue;
6884            }
6885            // caller is a full app, don't need to apply any other filtering
6886            if (ephemeralPkgName == null) {
6887                continue;
6888            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6889                // caller is same app; don't need to apply any other filtering
6890                continue;
6891            }
6892            // allow activities that have been explicitly exposed to ephemeral apps
6893            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6894            if (!isEphemeralApp
6895                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6896                continue;
6897            }
6898            resolveInfos.remove(i);
6899        }
6900        return resolveInfos;
6901    }
6902
6903    /**
6904     * Returns the activity component that can handle install failures.
6905     * <p>By default, the instant application installer handles failures. However, an
6906     * application may want to handle failures on its own. Applications do this by
6907     * creating an activity with an intent filter that handles the action
6908     * {@link Intent#ACTION_INSTALL_FAILURE}.
6909     */
6910    private @Nullable ComponentName findInstallFailureActivity(
6911            String packageName, int filterCallingUid, int userId) {
6912        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6913        failureActivityIntent.setPackage(packageName);
6914        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6915        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6916                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6917                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6918        final int NR = result.size();
6919        if (NR > 0) {
6920            for (int i = 0; i < NR; i++) {
6921                final ResolveInfo info = result.get(i);
6922                if (info.activityInfo.splitName != null) {
6923                    continue;
6924                }
6925                return new ComponentName(packageName, info.activityInfo.name);
6926            }
6927        }
6928        return null;
6929    }
6930
6931    /**
6932     * @param resolveInfos list of resolve infos in descending priority order
6933     * @return if the list contains a resolve info with non-negative priority
6934     */
6935    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6936        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6937    }
6938
6939    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6940            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6941            int userId) {
6942        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6943
6944        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6945            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6946                    candidates.size());
6947        }
6948
6949        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6950        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6951        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6952        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6953        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6954        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6955
6956        synchronized (mPackages) {
6957            final int count = candidates.size();
6958            // First, try to use linked apps. Partition the candidates into four lists:
6959            // one for the final results, one for the "do not use ever", one for "undefined status"
6960            // and finally one for "browser app type".
6961            for (int n=0; n<count; n++) {
6962                ResolveInfo info = candidates.get(n);
6963                String packageName = info.activityInfo.packageName;
6964                PackageSetting ps = mSettings.mPackages.get(packageName);
6965                if (ps != null) {
6966                    // Add to the special match all list (Browser use case)
6967                    if (info.handleAllWebDataURI) {
6968                        matchAllList.add(info);
6969                        continue;
6970                    }
6971                    // Try to get the status from User settings first
6972                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6973                    int status = (int)(packedStatus >> 32);
6974                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6975                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6976                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6977                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6978                                    + " : linkgen=" + linkGeneration);
6979                        }
6980                        // Use link-enabled generation as preferredOrder, i.e.
6981                        // prefer newly-enabled over earlier-enabled.
6982                        info.preferredOrder = linkGeneration;
6983                        alwaysList.add(info);
6984                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6985                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6986                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6987                        }
6988                        neverList.add(info);
6989                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6990                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6991                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6992                        }
6993                        alwaysAskList.add(info);
6994                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6995                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6996                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6997                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6998                        }
6999                        undefinedList.add(info);
7000                    }
7001                }
7002            }
7003
7004            // We'll want to include browser possibilities in a few cases
7005            boolean includeBrowser = false;
7006
7007            // First try to add the "always" resolution(s) for the current user, if any
7008            if (alwaysList.size() > 0) {
7009                result.addAll(alwaysList);
7010            } else {
7011                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7012                result.addAll(undefinedList);
7013                // Maybe add one for the other profile.
7014                if (xpDomainInfo != null && (
7015                        xpDomainInfo.bestDomainVerificationStatus
7016                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7017                    result.add(xpDomainInfo.resolveInfo);
7018                }
7019                includeBrowser = true;
7020            }
7021
7022            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7023            // If there were 'always' entries their preferred order has been set, so we also
7024            // back that off to make the alternatives equivalent
7025            if (alwaysAskList.size() > 0) {
7026                for (ResolveInfo i : result) {
7027                    i.preferredOrder = 0;
7028                }
7029                result.addAll(alwaysAskList);
7030                includeBrowser = true;
7031            }
7032
7033            if (includeBrowser) {
7034                // Also add browsers (all of them or only the default one)
7035                if (DEBUG_DOMAIN_VERIFICATION) {
7036                    Slog.v(TAG, "   ...including browsers in candidate set");
7037                }
7038                if ((matchFlags & MATCH_ALL) != 0) {
7039                    result.addAll(matchAllList);
7040                } else {
7041                    // Browser/generic handling case.  If there's a default browser, go straight
7042                    // to that (but only if there is no other higher-priority match).
7043                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7044                    int maxMatchPrio = 0;
7045                    ResolveInfo defaultBrowserMatch = null;
7046                    final int numCandidates = matchAllList.size();
7047                    for (int n = 0; n < numCandidates; n++) {
7048                        ResolveInfo info = matchAllList.get(n);
7049                        // track the highest overall match priority...
7050                        if (info.priority > maxMatchPrio) {
7051                            maxMatchPrio = info.priority;
7052                        }
7053                        // ...and the highest-priority default browser match
7054                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7055                            if (defaultBrowserMatch == null
7056                                    || (defaultBrowserMatch.priority < info.priority)) {
7057                                if (debug) {
7058                                    Slog.v(TAG, "Considering default browser match " + info);
7059                                }
7060                                defaultBrowserMatch = info;
7061                            }
7062                        }
7063                    }
7064                    if (defaultBrowserMatch != null
7065                            && defaultBrowserMatch.priority >= maxMatchPrio
7066                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7067                    {
7068                        if (debug) {
7069                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7070                        }
7071                        result.add(defaultBrowserMatch);
7072                    } else {
7073                        result.addAll(matchAllList);
7074                    }
7075                }
7076
7077                // If there is nothing selected, add all candidates and remove the ones that the user
7078                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7079                if (result.size() == 0) {
7080                    result.addAll(candidates);
7081                    result.removeAll(neverList);
7082                }
7083            }
7084        }
7085        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7086            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7087                    result.size());
7088            for (ResolveInfo info : result) {
7089                Slog.v(TAG, "  + " + info.activityInfo);
7090            }
7091        }
7092        return result;
7093    }
7094
7095    // Returns a packed value as a long:
7096    //
7097    // high 'int'-sized word: link status: undefined/ask/never/always.
7098    // low 'int'-sized word: relative priority among 'always' results.
7099    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7100        long result = ps.getDomainVerificationStatusForUser(userId);
7101        // if none available, get the master status
7102        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7103            if (ps.getIntentFilterVerificationInfo() != null) {
7104                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7105            }
7106        }
7107        return result;
7108    }
7109
7110    private ResolveInfo querySkipCurrentProfileIntents(
7111            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7112            int flags, int sourceUserId) {
7113        if (matchingFilters != null) {
7114            int size = matchingFilters.size();
7115            for (int i = 0; i < size; i ++) {
7116                CrossProfileIntentFilter filter = matchingFilters.get(i);
7117                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7118                    // Checking if there are activities in the target user that can handle the
7119                    // intent.
7120                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7121                            resolvedType, flags, sourceUserId);
7122                    if (resolveInfo != null) {
7123                        return resolveInfo;
7124                    }
7125                }
7126            }
7127        }
7128        return null;
7129    }
7130
7131    // Return matching ResolveInfo in target user if any.
7132    private ResolveInfo queryCrossProfileIntents(
7133            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7134            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7135        if (matchingFilters != null) {
7136            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7137            // match the same intent. For performance reasons, it is better not to
7138            // run queryIntent twice for the same userId
7139            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7140            int size = matchingFilters.size();
7141            for (int i = 0; i < size; i++) {
7142                CrossProfileIntentFilter filter = matchingFilters.get(i);
7143                int targetUserId = filter.getTargetUserId();
7144                boolean skipCurrentProfile =
7145                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7146                boolean skipCurrentProfileIfNoMatchFound =
7147                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7148                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7149                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7150                    // Checking if there are activities in the target user that can handle the
7151                    // intent.
7152                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7153                            resolvedType, flags, sourceUserId);
7154                    if (resolveInfo != null) return resolveInfo;
7155                    alreadyTriedUserIds.put(targetUserId, true);
7156                }
7157            }
7158        }
7159        return null;
7160    }
7161
7162    /**
7163     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7164     * will forward the intent to the filter's target user.
7165     * Otherwise, returns null.
7166     */
7167    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7168            String resolvedType, int flags, int sourceUserId) {
7169        int targetUserId = filter.getTargetUserId();
7170        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7171                resolvedType, flags, targetUserId);
7172        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7173            // If all the matches in the target profile are suspended, return null.
7174            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7175                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7176                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7177                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7178                            targetUserId);
7179                }
7180            }
7181        }
7182        return null;
7183    }
7184
7185    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7186            int sourceUserId, int targetUserId) {
7187        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7188        long ident = Binder.clearCallingIdentity();
7189        boolean targetIsProfile;
7190        try {
7191            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7192        } finally {
7193            Binder.restoreCallingIdentity(ident);
7194        }
7195        String className;
7196        if (targetIsProfile) {
7197            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7198        } else {
7199            className = FORWARD_INTENT_TO_PARENT;
7200        }
7201        ComponentName forwardingActivityComponentName = new ComponentName(
7202                mAndroidApplication.packageName, className);
7203        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7204                sourceUserId);
7205        if (!targetIsProfile) {
7206            forwardingActivityInfo.showUserIcon = targetUserId;
7207            forwardingResolveInfo.noResourceId = true;
7208        }
7209        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7210        forwardingResolveInfo.priority = 0;
7211        forwardingResolveInfo.preferredOrder = 0;
7212        forwardingResolveInfo.match = 0;
7213        forwardingResolveInfo.isDefault = true;
7214        forwardingResolveInfo.filter = filter;
7215        forwardingResolveInfo.targetUserId = targetUserId;
7216        return forwardingResolveInfo;
7217    }
7218
7219    @Override
7220    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7221            Intent[] specifics, String[] specificTypes, Intent intent,
7222            String resolvedType, int flags, int userId) {
7223        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7224                specificTypes, intent, resolvedType, flags, userId));
7225    }
7226
7227    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7228            Intent[] specifics, String[] specificTypes, Intent intent,
7229            String resolvedType, int flags, int userId) {
7230        if (!sUserManager.exists(userId)) return Collections.emptyList();
7231        final int callingUid = Binder.getCallingUid();
7232        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7233                false /*includeInstantApps*/);
7234        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7235                false /*requireFullPermission*/, false /*checkShell*/,
7236                "query intent activity options");
7237        final String resultsAction = intent.getAction();
7238
7239        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7240                | PackageManager.GET_RESOLVED_FILTER, userId);
7241
7242        if (DEBUG_INTENT_MATCHING) {
7243            Log.v(TAG, "Query " + intent + ": " + results);
7244        }
7245
7246        int specificsPos = 0;
7247        int N;
7248
7249        // todo: note that the algorithm used here is O(N^2).  This
7250        // isn't a problem in our current environment, but if we start running
7251        // into situations where we have more than 5 or 10 matches then this
7252        // should probably be changed to something smarter...
7253
7254        // First we go through and resolve each of the specific items
7255        // that were supplied, taking care of removing any corresponding
7256        // duplicate items in the generic resolve list.
7257        if (specifics != null) {
7258            for (int i=0; i<specifics.length; i++) {
7259                final Intent sintent = specifics[i];
7260                if (sintent == null) {
7261                    continue;
7262                }
7263
7264                if (DEBUG_INTENT_MATCHING) {
7265                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7266                }
7267
7268                String action = sintent.getAction();
7269                if (resultsAction != null && resultsAction.equals(action)) {
7270                    // If this action was explicitly requested, then don't
7271                    // remove things that have it.
7272                    action = null;
7273                }
7274
7275                ResolveInfo ri = null;
7276                ActivityInfo ai = null;
7277
7278                ComponentName comp = sintent.getComponent();
7279                if (comp == null) {
7280                    ri = resolveIntent(
7281                        sintent,
7282                        specificTypes != null ? specificTypes[i] : null,
7283                            flags, userId);
7284                    if (ri == null) {
7285                        continue;
7286                    }
7287                    if (ri == mResolveInfo) {
7288                        // ACK!  Must do something better with this.
7289                    }
7290                    ai = ri.activityInfo;
7291                    comp = new ComponentName(ai.applicationInfo.packageName,
7292                            ai.name);
7293                } else {
7294                    ai = getActivityInfo(comp, flags, userId);
7295                    if (ai == null) {
7296                        continue;
7297                    }
7298                }
7299
7300                // Look for any generic query activities that are duplicates
7301                // of this specific one, and remove them from the results.
7302                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7303                N = results.size();
7304                int j;
7305                for (j=specificsPos; j<N; j++) {
7306                    ResolveInfo sri = results.get(j);
7307                    if ((sri.activityInfo.name.equals(comp.getClassName())
7308                            && sri.activityInfo.applicationInfo.packageName.equals(
7309                                    comp.getPackageName()))
7310                        || (action != null && sri.filter.matchAction(action))) {
7311                        results.remove(j);
7312                        if (DEBUG_INTENT_MATCHING) Log.v(
7313                            TAG, "Removing duplicate item from " + j
7314                            + " due to specific " + specificsPos);
7315                        if (ri == null) {
7316                            ri = sri;
7317                        }
7318                        j--;
7319                        N--;
7320                    }
7321                }
7322
7323                // Add this specific item to its proper place.
7324                if (ri == null) {
7325                    ri = new ResolveInfo();
7326                    ri.activityInfo = ai;
7327                }
7328                results.add(specificsPos, ri);
7329                ri.specificIndex = i;
7330                specificsPos++;
7331            }
7332        }
7333
7334        // Now we go through the remaining generic results and remove any
7335        // duplicate actions that are found here.
7336        N = results.size();
7337        for (int i=specificsPos; i<N-1; i++) {
7338            final ResolveInfo rii = results.get(i);
7339            if (rii.filter == null) {
7340                continue;
7341            }
7342
7343            // Iterate over all of the actions of this result's intent
7344            // filter...  typically this should be just one.
7345            final Iterator<String> it = rii.filter.actionsIterator();
7346            if (it == null) {
7347                continue;
7348            }
7349            while (it.hasNext()) {
7350                final String action = it.next();
7351                if (resultsAction != null && resultsAction.equals(action)) {
7352                    // If this action was explicitly requested, then don't
7353                    // remove things that have it.
7354                    continue;
7355                }
7356                for (int j=i+1; j<N; j++) {
7357                    final ResolveInfo rij = results.get(j);
7358                    if (rij.filter != null && rij.filter.hasAction(action)) {
7359                        results.remove(j);
7360                        if (DEBUG_INTENT_MATCHING) Log.v(
7361                            TAG, "Removing duplicate item from " + j
7362                            + " due to action " + action + " at " + i);
7363                        j--;
7364                        N--;
7365                    }
7366                }
7367            }
7368
7369            // If the caller didn't request filter information, drop it now
7370            // so we don't have to marshall/unmarshall it.
7371            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7372                rii.filter = null;
7373            }
7374        }
7375
7376        // Filter out the caller activity if so requested.
7377        if (caller != null) {
7378            N = results.size();
7379            for (int i=0; i<N; i++) {
7380                ActivityInfo ainfo = results.get(i).activityInfo;
7381                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7382                        && caller.getClassName().equals(ainfo.name)) {
7383                    results.remove(i);
7384                    break;
7385                }
7386            }
7387        }
7388
7389        // If the caller didn't request filter information,
7390        // drop them now so we don't have to
7391        // marshall/unmarshall it.
7392        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7393            N = results.size();
7394            for (int i=0; i<N; i++) {
7395                results.get(i).filter = null;
7396            }
7397        }
7398
7399        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7400        return results;
7401    }
7402
7403    @Override
7404    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7405            String resolvedType, int flags, int userId) {
7406        return new ParceledListSlice<>(
7407                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7408                        false /*allowDynamicSplits*/));
7409    }
7410
7411    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7412            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7413        if (!sUserManager.exists(userId)) return Collections.emptyList();
7414        final int callingUid = Binder.getCallingUid();
7415        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7416                false /*requireFullPermission*/, false /*checkShell*/,
7417                "query intent receivers");
7418        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7419        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7420                false /*includeInstantApps*/);
7421        ComponentName comp = intent.getComponent();
7422        if (comp == null) {
7423            if (intent.getSelector() != null) {
7424                intent = intent.getSelector();
7425                comp = intent.getComponent();
7426            }
7427        }
7428        if (comp != null) {
7429            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7430            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7431            if (ai != null) {
7432                // When specifying an explicit component, we prevent the activity from being
7433                // used when either 1) the calling package is normal and the activity is within
7434                // an instant application or 2) the calling package is ephemeral and the
7435                // activity is not visible to instant applications.
7436                final boolean matchInstantApp =
7437                        (flags & PackageManager.MATCH_INSTANT) != 0;
7438                final boolean matchVisibleToInstantAppOnly =
7439                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7440                final boolean matchExplicitlyVisibleOnly =
7441                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7442                final boolean isCallerInstantApp =
7443                        instantAppPkgName != null;
7444                final boolean isTargetSameInstantApp =
7445                        comp.getPackageName().equals(instantAppPkgName);
7446                final boolean isTargetInstantApp =
7447                        (ai.applicationInfo.privateFlags
7448                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7449                final boolean isTargetVisibleToInstantApp =
7450                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7451                final boolean isTargetExplicitlyVisibleToInstantApp =
7452                        isTargetVisibleToInstantApp
7453                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7454                final boolean isTargetHiddenFromInstantApp =
7455                        !isTargetVisibleToInstantApp
7456                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7457                final boolean blockResolution =
7458                        !isTargetSameInstantApp
7459                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7460                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7461                                        && isTargetHiddenFromInstantApp));
7462                if (!blockResolution) {
7463                    ResolveInfo ri = new ResolveInfo();
7464                    ri.activityInfo = ai;
7465                    list.add(ri);
7466                }
7467            }
7468            return applyPostResolutionFilter(
7469                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7470        }
7471
7472        // reader
7473        synchronized (mPackages) {
7474            String pkgName = intent.getPackage();
7475            if (pkgName == null) {
7476                final List<ResolveInfo> result =
7477                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7478                return applyPostResolutionFilter(
7479                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7480            }
7481            final PackageParser.Package pkg = mPackages.get(pkgName);
7482            if (pkg != null) {
7483                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7484                        intent, resolvedType, flags, pkg.receivers, userId);
7485                return applyPostResolutionFilter(
7486                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7487            }
7488            return Collections.emptyList();
7489        }
7490    }
7491
7492    @Override
7493    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7494        final int callingUid = Binder.getCallingUid();
7495        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7496    }
7497
7498    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7499            int userId, int callingUid) {
7500        if (!sUserManager.exists(userId)) return null;
7501        flags = updateFlagsForResolve(
7502                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7503        List<ResolveInfo> query = queryIntentServicesInternal(
7504                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7505        if (query != null) {
7506            if (query.size() >= 1) {
7507                // If there is more than one service with the same priority,
7508                // just arbitrarily pick the first one.
7509                return query.get(0);
7510            }
7511        }
7512        return null;
7513    }
7514
7515    @Override
7516    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7517            String resolvedType, int flags, int userId) {
7518        final int callingUid = Binder.getCallingUid();
7519        return new ParceledListSlice<>(queryIntentServicesInternal(
7520                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7521    }
7522
7523    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7524            String resolvedType, int flags, int userId, int callingUid,
7525            boolean includeInstantApps) {
7526        if (!sUserManager.exists(userId)) return Collections.emptyList();
7527        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7528                false /*requireFullPermission*/, false /*checkShell*/,
7529                "query intent receivers");
7530        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7531        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7532        ComponentName comp = intent.getComponent();
7533        if (comp == null) {
7534            if (intent.getSelector() != null) {
7535                intent = intent.getSelector();
7536                comp = intent.getComponent();
7537            }
7538        }
7539        if (comp != null) {
7540            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7541            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7542            if (si != null) {
7543                // When specifying an explicit component, we prevent the service from being
7544                // used when either 1) the service is in an instant application and the
7545                // caller is not the same instant application or 2) the calling package is
7546                // ephemeral and the activity is not visible to ephemeral applications.
7547                final boolean matchInstantApp =
7548                        (flags & PackageManager.MATCH_INSTANT) != 0;
7549                final boolean matchVisibleToInstantAppOnly =
7550                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7551                final boolean isCallerInstantApp =
7552                        instantAppPkgName != null;
7553                final boolean isTargetSameInstantApp =
7554                        comp.getPackageName().equals(instantAppPkgName);
7555                final boolean isTargetInstantApp =
7556                        (si.applicationInfo.privateFlags
7557                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7558                final boolean isTargetHiddenFromInstantApp =
7559                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7560                final boolean blockResolution =
7561                        !isTargetSameInstantApp
7562                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7563                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7564                                        && isTargetHiddenFromInstantApp));
7565                if (!blockResolution) {
7566                    final ResolveInfo ri = new ResolveInfo();
7567                    ri.serviceInfo = si;
7568                    list.add(ri);
7569                }
7570            }
7571            return list;
7572        }
7573
7574        // reader
7575        synchronized (mPackages) {
7576            String pkgName = intent.getPackage();
7577            if (pkgName == null) {
7578                return applyPostServiceResolutionFilter(
7579                        mServices.queryIntent(intent, resolvedType, flags, userId),
7580                        instantAppPkgName);
7581            }
7582            final PackageParser.Package pkg = mPackages.get(pkgName);
7583            if (pkg != null) {
7584                return applyPostServiceResolutionFilter(
7585                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7586                                userId),
7587                        instantAppPkgName);
7588            }
7589            return Collections.emptyList();
7590        }
7591    }
7592
7593    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7594            String instantAppPkgName) {
7595        if (instantAppPkgName == null) {
7596            return resolveInfos;
7597        }
7598        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7599            final ResolveInfo info = resolveInfos.get(i);
7600            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7601            // allow services that are defined in the provided package
7602            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7603                if (info.serviceInfo.splitName != null
7604                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7605                                info.serviceInfo.splitName)) {
7606                    // requested service is defined in a split that hasn't been installed yet.
7607                    // add the installer to the resolve list
7608                    if (DEBUG_INSTANT) {
7609                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7610                    }
7611                    final ResolveInfo installerInfo = new ResolveInfo(
7612                            mInstantAppInstallerInfo);
7613                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7614                            null /* installFailureActivity */,
7615                            info.serviceInfo.packageName,
7616                            info.serviceInfo.applicationInfo.versionCode,
7617                            info.serviceInfo.splitName);
7618                    // make sure this resolver is the default
7619                    installerInfo.isDefault = true;
7620                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7621                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7622                    // add a non-generic filter
7623                    installerInfo.filter = new IntentFilter();
7624                    // load resources from the correct package
7625                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7626                    resolveInfos.set(i, installerInfo);
7627                }
7628                continue;
7629            }
7630            // allow services that have been explicitly exposed to ephemeral apps
7631            if (!isEphemeralApp
7632                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7633                continue;
7634            }
7635            resolveInfos.remove(i);
7636        }
7637        return resolveInfos;
7638    }
7639
7640    @Override
7641    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7642            String resolvedType, int flags, int userId) {
7643        return new ParceledListSlice<>(
7644                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7645    }
7646
7647    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7648            Intent intent, String resolvedType, int flags, int userId) {
7649        if (!sUserManager.exists(userId)) return Collections.emptyList();
7650        final int callingUid = Binder.getCallingUid();
7651        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7652        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7653                false /*includeInstantApps*/);
7654        ComponentName comp = intent.getComponent();
7655        if (comp == null) {
7656            if (intent.getSelector() != null) {
7657                intent = intent.getSelector();
7658                comp = intent.getComponent();
7659            }
7660        }
7661        if (comp != null) {
7662            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7663            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7664            if (pi != null) {
7665                // When specifying an explicit component, we prevent the provider from being
7666                // used when either 1) the provider is in an instant application and the
7667                // caller is not the same instant application or 2) the calling package is an
7668                // instant application and the provider is not visible to instant applications.
7669                final boolean matchInstantApp =
7670                        (flags & PackageManager.MATCH_INSTANT) != 0;
7671                final boolean matchVisibleToInstantAppOnly =
7672                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7673                final boolean isCallerInstantApp =
7674                        instantAppPkgName != null;
7675                final boolean isTargetSameInstantApp =
7676                        comp.getPackageName().equals(instantAppPkgName);
7677                final boolean isTargetInstantApp =
7678                        (pi.applicationInfo.privateFlags
7679                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7680                final boolean isTargetHiddenFromInstantApp =
7681                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7682                final boolean blockResolution =
7683                        !isTargetSameInstantApp
7684                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7685                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7686                                        && isTargetHiddenFromInstantApp));
7687                if (!blockResolution) {
7688                    final ResolveInfo ri = new ResolveInfo();
7689                    ri.providerInfo = pi;
7690                    list.add(ri);
7691                }
7692            }
7693            return list;
7694        }
7695
7696        // reader
7697        synchronized (mPackages) {
7698            String pkgName = intent.getPackage();
7699            if (pkgName == null) {
7700                return applyPostContentProviderResolutionFilter(
7701                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7702                        instantAppPkgName);
7703            }
7704            final PackageParser.Package pkg = mPackages.get(pkgName);
7705            if (pkg != null) {
7706                return applyPostContentProviderResolutionFilter(
7707                        mProviders.queryIntentForPackage(
7708                        intent, resolvedType, flags, pkg.providers, userId),
7709                        instantAppPkgName);
7710            }
7711            return Collections.emptyList();
7712        }
7713    }
7714
7715    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7716            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7717        if (instantAppPkgName == null) {
7718            return resolveInfos;
7719        }
7720        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7721            final ResolveInfo info = resolveInfos.get(i);
7722            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7723            // allow providers that are defined in the provided package
7724            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7725                if (info.providerInfo.splitName != null
7726                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7727                                info.providerInfo.splitName)) {
7728                    // requested provider is defined in a split that hasn't been installed yet.
7729                    // add the installer to the resolve list
7730                    if (DEBUG_INSTANT) {
7731                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7732                    }
7733                    final ResolveInfo installerInfo = new ResolveInfo(
7734                            mInstantAppInstallerInfo);
7735                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7736                            null /*failureActivity*/,
7737                            info.providerInfo.packageName,
7738                            info.providerInfo.applicationInfo.versionCode,
7739                            info.providerInfo.splitName);
7740                    // make sure this resolver is the default
7741                    installerInfo.isDefault = true;
7742                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7743                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7744                    // add a non-generic filter
7745                    installerInfo.filter = new IntentFilter();
7746                    // load resources from the correct package
7747                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7748                    resolveInfos.set(i, installerInfo);
7749                }
7750                continue;
7751            }
7752            // allow providers that have been explicitly exposed to instant applications
7753            if (!isEphemeralApp
7754                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7755                continue;
7756            }
7757            resolveInfos.remove(i);
7758        }
7759        return resolveInfos;
7760    }
7761
7762    @Override
7763    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7764        final int callingUid = Binder.getCallingUid();
7765        if (getInstantAppPackageName(callingUid) != null) {
7766            return ParceledListSlice.emptyList();
7767        }
7768        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7769        flags = updateFlagsForPackage(flags, userId, null);
7770        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7771        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7772                true /* requireFullPermission */, false /* checkShell */,
7773                "get installed packages");
7774
7775        // writer
7776        synchronized (mPackages) {
7777            ArrayList<PackageInfo> list;
7778            if (listUninstalled) {
7779                list = new ArrayList<>(mSettings.mPackages.size());
7780                for (PackageSetting ps : mSettings.mPackages.values()) {
7781                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7782                        continue;
7783                    }
7784                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7785                        continue;
7786                    }
7787                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7788                    if (pi != null) {
7789                        list.add(pi);
7790                    }
7791                }
7792            } else {
7793                list = new ArrayList<>(mPackages.size());
7794                for (PackageParser.Package p : mPackages.values()) {
7795                    final PackageSetting ps = (PackageSetting) p.mExtras;
7796                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7797                        continue;
7798                    }
7799                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7800                        continue;
7801                    }
7802                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7803                            p.mExtras, flags, userId);
7804                    if (pi != null) {
7805                        list.add(pi);
7806                    }
7807                }
7808            }
7809
7810            return new ParceledListSlice<>(list);
7811        }
7812    }
7813
7814    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7815            String[] permissions, boolean[] tmp, int flags, int userId) {
7816        int numMatch = 0;
7817        final PermissionsState permissionsState = ps.getPermissionsState();
7818        for (int i=0; i<permissions.length; i++) {
7819            final String permission = permissions[i];
7820            if (permissionsState.hasPermission(permission, userId)) {
7821                tmp[i] = true;
7822                numMatch++;
7823            } else {
7824                tmp[i] = false;
7825            }
7826        }
7827        if (numMatch == 0) {
7828            return;
7829        }
7830        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7831
7832        // The above might return null in cases of uninstalled apps or install-state
7833        // skew across users/profiles.
7834        if (pi != null) {
7835            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7836                if (numMatch == permissions.length) {
7837                    pi.requestedPermissions = permissions;
7838                } else {
7839                    pi.requestedPermissions = new String[numMatch];
7840                    numMatch = 0;
7841                    for (int i=0; i<permissions.length; i++) {
7842                        if (tmp[i]) {
7843                            pi.requestedPermissions[numMatch] = permissions[i];
7844                            numMatch++;
7845                        }
7846                    }
7847                }
7848            }
7849            list.add(pi);
7850        }
7851    }
7852
7853    @Override
7854    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7855            String[] permissions, int flags, int userId) {
7856        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7857        flags = updateFlagsForPackage(flags, userId, permissions);
7858        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7859                true /* requireFullPermission */, false /* checkShell */,
7860                "get packages holding permissions");
7861        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7862
7863        // writer
7864        synchronized (mPackages) {
7865            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7866            boolean[] tmpBools = new boolean[permissions.length];
7867            if (listUninstalled) {
7868                for (PackageSetting ps : mSettings.mPackages.values()) {
7869                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7870                            userId);
7871                }
7872            } else {
7873                for (PackageParser.Package pkg : mPackages.values()) {
7874                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7875                    if (ps != null) {
7876                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7877                                userId);
7878                    }
7879                }
7880            }
7881
7882            return new ParceledListSlice<PackageInfo>(list);
7883        }
7884    }
7885
7886    @Override
7887    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7888        final int callingUid = Binder.getCallingUid();
7889        if (getInstantAppPackageName(callingUid) != null) {
7890            return ParceledListSlice.emptyList();
7891        }
7892        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7893        flags = updateFlagsForApplication(flags, userId, null);
7894        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7895
7896        // writer
7897        synchronized (mPackages) {
7898            ArrayList<ApplicationInfo> list;
7899            if (listUninstalled) {
7900                list = new ArrayList<>(mSettings.mPackages.size());
7901                for (PackageSetting ps : mSettings.mPackages.values()) {
7902                    ApplicationInfo ai;
7903                    int effectiveFlags = flags;
7904                    if (ps.isSystem()) {
7905                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7906                    }
7907                    if (ps.pkg != null) {
7908                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7909                            continue;
7910                        }
7911                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7912                            continue;
7913                        }
7914                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7915                                ps.readUserState(userId), userId);
7916                        if (ai != null) {
7917                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7918                        }
7919                    } else {
7920                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7921                        // and already converts to externally visible package name
7922                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7923                                callingUid, effectiveFlags, userId);
7924                    }
7925                    if (ai != null) {
7926                        list.add(ai);
7927                    }
7928                }
7929            } else {
7930                list = new ArrayList<>(mPackages.size());
7931                for (PackageParser.Package p : mPackages.values()) {
7932                    if (p.mExtras != null) {
7933                        PackageSetting ps = (PackageSetting) p.mExtras;
7934                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7935                            continue;
7936                        }
7937                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7938                            continue;
7939                        }
7940                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7941                                ps.readUserState(userId), userId);
7942                        if (ai != null) {
7943                            ai.packageName = resolveExternalPackageNameLPr(p);
7944                            list.add(ai);
7945                        }
7946                    }
7947                }
7948            }
7949
7950            return new ParceledListSlice<>(list);
7951        }
7952    }
7953
7954    @Override
7955    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7956        if (HIDE_EPHEMERAL_APIS) {
7957            return null;
7958        }
7959        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7960            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7961                    "getEphemeralApplications");
7962        }
7963        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7964                true /* requireFullPermission */, false /* checkShell */,
7965                "getEphemeralApplications");
7966        synchronized (mPackages) {
7967            List<InstantAppInfo> instantApps = mInstantAppRegistry
7968                    .getInstantAppsLPr(userId);
7969            if (instantApps != null) {
7970                return new ParceledListSlice<>(instantApps);
7971            }
7972        }
7973        return null;
7974    }
7975
7976    @Override
7977    public boolean isInstantApp(String packageName, int userId) {
7978        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7979                true /* requireFullPermission */, false /* checkShell */,
7980                "isInstantApp");
7981        if (HIDE_EPHEMERAL_APIS) {
7982            return false;
7983        }
7984
7985        synchronized (mPackages) {
7986            int callingUid = Binder.getCallingUid();
7987            if (Process.isIsolated(callingUid)) {
7988                callingUid = mIsolatedOwners.get(callingUid);
7989            }
7990            final PackageSetting ps = mSettings.mPackages.get(packageName);
7991            PackageParser.Package pkg = mPackages.get(packageName);
7992            final boolean returnAllowed =
7993                    ps != null
7994                    && (isCallerSameApp(packageName, callingUid)
7995                            || canViewInstantApps(callingUid, userId)
7996                            || mInstantAppRegistry.isInstantAccessGranted(
7997                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7998            if (returnAllowed) {
7999                return ps.getInstantApp(userId);
8000            }
8001        }
8002        return false;
8003    }
8004
8005    @Override
8006    public byte[] getInstantAppCookie(String packageName, int userId) {
8007        if (HIDE_EPHEMERAL_APIS) {
8008            return null;
8009        }
8010
8011        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8012                true /* requireFullPermission */, false /* checkShell */,
8013                "getInstantAppCookie");
8014        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8015            return null;
8016        }
8017        synchronized (mPackages) {
8018            return mInstantAppRegistry.getInstantAppCookieLPw(
8019                    packageName, userId);
8020        }
8021    }
8022
8023    @Override
8024    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8025        if (HIDE_EPHEMERAL_APIS) {
8026            return true;
8027        }
8028
8029        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8030                true /* requireFullPermission */, true /* checkShell */,
8031                "setInstantAppCookie");
8032        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8033            return false;
8034        }
8035        synchronized (mPackages) {
8036            return mInstantAppRegistry.setInstantAppCookieLPw(
8037                    packageName, cookie, userId);
8038        }
8039    }
8040
8041    @Override
8042    public Bitmap getInstantAppIcon(String packageName, int userId) {
8043        if (HIDE_EPHEMERAL_APIS) {
8044            return null;
8045        }
8046
8047        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8048            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8049                    "getInstantAppIcon");
8050        }
8051        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8052                true /* requireFullPermission */, false /* checkShell */,
8053                "getInstantAppIcon");
8054
8055        synchronized (mPackages) {
8056            return mInstantAppRegistry.getInstantAppIconLPw(
8057                    packageName, userId);
8058        }
8059    }
8060
8061    private boolean isCallerSameApp(String packageName, int uid) {
8062        PackageParser.Package pkg = mPackages.get(packageName);
8063        return pkg != null
8064                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8065    }
8066
8067    @Override
8068    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8069        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8070            return ParceledListSlice.emptyList();
8071        }
8072        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8073    }
8074
8075    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8076        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8077
8078        // reader
8079        synchronized (mPackages) {
8080            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8081            final int userId = UserHandle.getCallingUserId();
8082            while (i.hasNext()) {
8083                final PackageParser.Package p = i.next();
8084                if (p.applicationInfo == null) continue;
8085
8086                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8087                        && !p.applicationInfo.isDirectBootAware();
8088                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8089                        && p.applicationInfo.isDirectBootAware();
8090
8091                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8092                        && (!mSafeMode || isSystemApp(p))
8093                        && (matchesUnaware || matchesAware)) {
8094                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8095                    if (ps != null) {
8096                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8097                                ps.readUserState(userId), userId);
8098                        if (ai != null) {
8099                            finalList.add(ai);
8100                        }
8101                    }
8102                }
8103            }
8104        }
8105
8106        return finalList;
8107    }
8108
8109    @Override
8110    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8111        return resolveContentProviderInternal(name, flags, userId);
8112    }
8113
8114    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8115        if (!sUserManager.exists(userId)) return null;
8116        flags = updateFlagsForComponent(flags, userId, name);
8117        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8118        // reader
8119        synchronized (mPackages) {
8120            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8121            PackageSetting ps = provider != null
8122                    ? mSettings.mPackages.get(provider.owner.packageName)
8123                    : null;
8124            if (ps != null) {
8125                final boolean isInstantApp = ps.getInstantApp(userId);
8126                // normal application; filter out instant application provider
8127                if (instantAppPkgName == null && isInstantApp) {
8128                    return null;
8129                }
8130                // instant application; filter out other instant applications
8131                if (instantAppPkgName != null
8132                        && isInstantApp
8133                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8134                    return null;
8135                }
8136                // instant application; filter out non-exposed provider
8137                if (instantAppPkgName != null
8138                        && !isInstantApp
8139                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8140                    return null;
8141                }
8142                // provider not enabled
8143                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8144                    return null;
8145                }
8146                return PackageParser.generateProviderInfo(
8147                        provider, flags, ps.readUserState(userId), userId);
8148            }
8149            return null;
8150        }
8151    }
8152
8153    /**
8154     * @deprecated
8155     */
8156    @Deprecated
8157    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8158        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8159            return;
8160        }
8161        // reader
8162        synchronized (mPackages) {
8163            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8164                    .entrySet().iterator();
8165            final int userId = UserHandle.getCallingUserId();
8166            while (i.hasNext()) {
8167                Map.Entry<String, PackageParser.Provider> entry = i.next();
8168                PackageParser.Provider p = entry.getValue();
8169                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8170
8171                if (ps != null && p.syncable
8172                        && (!mSafeMode || (p.info.applicationInfo.flags
8173                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8174                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8175                            ps.readUserState(userId), userId);
8176                    if (info != null) {
8177                        outNames.add(entry.getKey());
8178                        outInfo.add(info);
8179                    }
8180                }
8181            }
8182        }
8183    }
8184
8185    @Override
8186    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8187            int uid, int flags, String metaDataKey) {
8188        final int callingUid = Binder.getCallingUid();
8189        final int userId = processName != null ? UserHandle.getUserId(uid)
8190                : UserHandle.getCallingUserId();
8191        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8192        flags = updateFlagsForComponent(flags, userId, processName);
8193        ArrayList<ProviderInfo> finalList = null;
8194        // reader
8195        synchronized (mPackages) {
8196            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8197            while (i.hasNext()) {
8198                final PackageParser.Provider p = i.next();
8199                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8200                if (ps != null && p.info.authority != null
8201                        && (processName == null
8202                                || (p.info.processName.equals(processName)
8203                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8204                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8205
8206                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8207                    // parameter.
8208                    if (metaDataKey != null
8209                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8210                        continue;
8211                    }
8212                    final ComponentName component =
8213                            new ComponentName(p.info.packageName, p.info.name);
8214                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8215                        continue;
8216                    }
8217                    if (finalList == null) {
8218                        finalList = new ArrayList<ProviderInfo>(3);
8219                    }
8220                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8221                            ps.readUserState(userId), userId);
8222                    if (info != null) {
8223                        finalList.add(info);
8224                    }
8225                }
8226            }
8227        }
8228
8229        if (finalList != null) {
8230            Collections.sort(finalList, mProviderInitOrderSorter);
8231            return new ParceledListSlice<ProviderInfo>(finalList);
8232        }
8233
8234        return ParceledListSlice.emptyList();
8235    }
8236
8237    @Override
8238    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8239        // reader
8240        synchronized (mPackages) {
8241            final int callingUid = Binder.getCallingUid();
8242            final int callingUserId = UserHandle.getUserId(callingUid);
8243            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8244            if (ps == null) return null;
8245            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8246                return null;
8247            }
8248            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8249            return PackageParser.generateInstrumentationInfo(i, flags);
8250        }
8251    }
8252
8253    @Override
8254    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8255            String targetPackage, int flags) {
8256        final int callingUid = Binder.getCallingUid();
8257        final int callingUserId = UserHandle.getUserId(callingUid);
8258        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8259        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8260            return ParceledListSlice.emptyList();
8261        }
8262        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8263    }
8264
8265    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8266            int flags) {
8267        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8268
8269        // reader
8270        synchronized (mPackages) {
8271            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8272            while (i.hasNext()) {
8273                final PackageParser.Instrumentation p = i.next();
8274                if (targetPackage == null
8275                        || targetPackage.equals(p.info.targetPackage)) {
8276                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8277                            flags);
8278                    if (ii != null) {
8279                        finalList.add(ii);
8280                    }
8281                }
8282            }
8283        }
8284
8285        return finalList;
8286    }
8287
8288    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8289        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8290        try {
8291            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8292        } finally {
8293            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8294        }
8295    }
8296
8297    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8298        final File[] files = scanDir.listFiles();
8299        if (ArrayUtils.isEmpty(files)) {
8300            Log.d(TAG, "No files in app dir " + scanDir);
8301            return;
8302        }
8303
8304        if (DEBUG_PACKAGE_SCANNING) {
8305            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8306                    + " flags=0x" + Integer.toHexString(parseFlags));
8307        }
8308        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8309                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8310                mParallelPackageParserCallback)) {
8311            // Submit files for parsing in parallel
8312            int fileCount = 0;
8313            for (File file : files) {
8314                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8315                        && !PackageInstallerService.isStageName(file.getName());
8316                if (!isPackage) {
8317                    // Ignore entries which are not packages
8318                    continue;
8319                }
8320                parallelPackageParser.submit(file, parseFlags);
8321                fileCount++;
8322            }
8323
8324            // Process results one by one
8325            for (; fileCount > 0; fileCount--) {
8326                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8327                Throwable throwable = parseResult.throwable;
8328                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8329
8330                if (throwable == null) {
8331                    // TODO(toddke): move lower in the scan chain
8332                    // Static shared libraries have synthetic package names
8333                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8334                        renameStaticSharedLibraryPackage(parseResult.pkg);
8335                    }
8336                    try {
8337                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8338                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8339                                    currentTime, null);
8340                        }
8341                    } catch (PackageManagerException e) {
8342                        errorCode = e.error;
8343                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8344                    }
8345                } else if (throwable instanceof PackageParser.PackageParserException) {
8346                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8347                            throwable;
8348                    errorCode = e.error;
8349                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8350                } else {
8351                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8352                            + parseResult.scanFile, throwable);
8353                }
8354
8355                // Delete invalid userdata apps
8356                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8357                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8358                    logCriticalInfo(Log.WARN,
8359                            "Deleting invalid package at " + parseResult.scanFile);
8360                    removeCodePathLI(parseResult.scanFile);
8361                }
8362            }
8363        }
8364    }
8365
8366    public static void reportSettingsProblem(int priority, String msg) {
8367        logCriticalInfo(priority, msg);
8368    }
8369
8370    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8371            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8372        // When upgrading from pre-N MR1, verify the package time stamp using the package
8373        // directory and not the APK file.
8374        final long lastModifiedTime = mIsPreNMR1Upgrade
8375                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8376        if (ps != null && !forceCollect
8377                && ps.codePathString.equals(pkg.codePath)
8378                && ps.timeStamp == lastModifiedTime
8379                && !isCompatSignatureUpdateNeeded(pkg)
8380                && !isRecoverSignatureUpdateNeeded(pkg)) {
8381            if (ps.signatures.mSigningDetails.signatures != null
8382                    && ps.signatures.mSigningDetails.signatures.length != 0
8383                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8384                            != SignatureSchemeVersion.UNKNOWN) {
8385                // Optimization: reuse the existing cached signing data
8386                // if the package appears to be unchanged.
8387                pkg.mSigningDetails =
8388                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8389                return;
8390            }
8391
8392            Slog.w(TAG, "PackageSetting for " + ps.name
8393                    + " is missing signatures.  Collecting certs again to recover them.");
8394        } else {
8395            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8396                    (forceCollect ? " (forced)" : ""));
8397        }
8398
8399        try {
8400            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8401            PackageParser.collectCertificates(pkg, skipVerify);
8402        } catch (PackageParserException e) {
8403            throw PackageManagerException.from(e);
8404        } finally {
8405            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8406        }
8407    }
8408
8409    /**
8410     *  Traces a package scan.
8411     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8412     */
8413    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8414            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8415        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8416        try {
8417            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8418        } finally {
8419            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8420        }
8421    }
8422
8423    /**
8424     *  Scans a package and returns the newly parsed package.
8425     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8426     */
8427    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8428            long currentTime, UserHandle user) throws PackageManagerException {
8429        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8430        PackageParser pp = new PackageParser();
8431        pp.setSeparateProcesses(mSeparateProcesses);
8432        pp.setOnlyCoreApps(mOnlyCore);
8433        pp.setDisplayMetrics(mMetrics);
8434        pp.setCallback(mPackageParserCallback);
8435
8436        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8437        final PackageParser.Package pkg;
8438        try {
8439            pkg = pp.parsePackage(scanFile, parseFlags);
8440        } catch (PackageParserException e) {
8441            throw PackageManagerException.from(e);
8442        } finally {
8443            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8444        }
8445
8446        // Static shared libraries have synthetic package names
8447        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8448            renameStaticSharedLibraryPackage(pkg);
8449        }
8450
8451        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8452    }
8453
8454    /**
8455     *  Scans a package and returns the newly parsed package.
8456     *  @throws PackageManagerException on a parse error.
8457     */
8458    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8459            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8460            @Nullable UserHandle user)
8461                    throws PackageManagerException {
8462        // If the package has children and this is the first dive in the function
8463        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8464        // packages (parent and children) would be successfully scanned before the
8465        // actual scan since scanning mutates internal state and we want to atomically
8466        // install the package and its children.
8467        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8468            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8469                scanFlags |= SCAN_CHECK_ONLY;
8470            }
8471        } else {
8472            scanFlags &= ~SCAN_CHECK_ONLY;
8473        }
8474
8475        // Scan the parent
8476        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8477                scanFlags, currentTime, user);
8478
8479        // Scan the children
8480        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8481        for (int i = 0; i < childCount; i++) {
8482            PackageParser.Package childPackage = pkg.childPackages.get(i);
8483            addForInitLI(childPackage, parseFlags, scanFlags,
8484                    currentTime, user);
8485        }
8486
8487
8488        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8489            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8490        }
8491
8492        return scannedPkg;
8493    }
8494
8495    /**
8496     * Returns if full apk verification can be skipped for the whole package, including the splits.
8497     */
8498    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8499        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8500            return false;
8501        }
8502        // TODO: Allow base and splits to be verified individually.
8503        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8504            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8505                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8506                    return false;
8507                }
8508            }
8509        }
8510        return true;
8511    }
8512
8513    /**
8514     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8515     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8516     * match one in a trusted source, and should be done separately.
8517     */
8518    private boolean canSkipFullApkVerification(String apkPath) {
8519        byte[] rootHashObserved = null;
8520        try {
8521            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8522            if (rootHashObserved == null) {
8523                return false;  // APK does not contain Merkle tree root hash.
8524            }
8525            synchronized (mInstallLock) {
8526                // Returns whether the observed root hash matches what kernel has.
8527                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8528                return true;
8529            }
8530        } catch (InstallerException | IOException | DigestException |
8531                NoSuchAlgorithmException e) {
8532            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8533        }
8534        return false;
8535    }
8536
8537    /**
8538     * Adds a new package to the internal data structures during platform initialization.
8539     * <p>After adding, the package is known to the system and available for querying.
8540     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8541     * etc...], additional checks are performed. Basic verification [such as ensuring
8542     * matching signatures, checking version codes, etc...] occurs if the package is
8543     * identical to a previously known package. If the package fails a signature check,
8544     * the version installed on /data will be removed. If the version of the new package
8545     * is less than or equal than the version on /data, it will be ignored.
8546     * <p>Regardless of the package location, the results are applied to the internal
8547     * structures and the package is made available to the rest of the system.
8548     * <p>NOTE: The return value should be removed. It's the passed in package object.
8549     */
8550    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8551            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8552            @Nullable UserHandle user)
8553                    throws PackageManagerException {
8554        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8555        final String renamedPkgName;
8556        final PackageSetting disabledPkgSetting;
8557        final boolean isSystemPkgUpdated;
8558        final boolean pkgAlreadyExists;
8559        PackageSetting pkgSetting;
8560
8561        // NOTE: installPackageLI() has the same code to setup the package's
8562        // application info. This probably should be done lower in the call
8563        // stack [such as scanPackageOnly()]. However, we verify the application
8564        // info prior to that [in scanPackageNew()] and thus have to setup
8565        // the application info early.
8566        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8567        pkg.setApplicationInfoCodePath(pkg.codePath);
8568        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8569        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8570        pkg.setApplicationInfoResourcePath(pkg.codePath);
8571        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8572        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8573
8574        synchronized (mPackages) {
8575            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8576            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8577            if (realPkgName != null) {
8578                ensurePackageRenamed(pkg, renamedPkgName);
8579            }
8580            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8581            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8582            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8583            pkgAlreadyExists = pkgSetting != null;
8584            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8585            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8586            isSystemPkgUpdated = disabledPkgSetting != null;
8587
8588            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8589                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8590            }
8591
8592            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8593                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8594                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8595                    : null;
8596            if (DEBUG_PACKAGE_SCANNING
8597                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8598                    && sharedUserSetting != null) {
8599                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8600                        + " (uid=" + sharedUserSetting.userId + "):"
8601                        + " packages=" + sharedUserSetting.packages);
8602            }
8603
8604            if (scanSystemPartition) {
8605                // Potentially prune child packages. If the application on the /system
8606                // partition has been updated via OTA, but, is still disabled by a
8607                // version on /data, cycle through all of its children packages and
8608                // remove children that are no longer defined.
8609                if (isSystemPkgUpdated) {
8610                    final int scannedChildCount = (pkg.childPackages != null)
8611                            ? pkg.childPackages.size() : 0;
8612                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8613                            ? disabledPkgSetting.childPackageNames.size() : 0;
8614                    for (int i = 0; i < disabledChildCount; i++) {
8615                        String disabledChildPackageName =
8616                                disabledPkgSetting.childPackageNames.get(i);
8617                        boolean disabledPackageAvailable = false;
8618                        for (int j = 0; j < scannedChildCount; j++) {
8619                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8620                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8621                                disabledPackageAvailable = true;
8622                                break;
8623                            }
8624                        }
8625                        if (!disabledPackageAvailable) {
8626                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8627                        }
8628                    }
8629                    // we're updating the disabled package, so, scan it as the package setting
8630                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8631                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8632                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8633                            (pkg == mPlatformPackage), user);
8634                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8635                }
8636            }
8637        }
8638
8639        final boolean newPkgChangedPaths =
8640                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8641        final boolean newPkgVersionGreater =
8642                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8643        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8644                && newPkgChangedPaths && newPkgVersionGreater;
8645        if (isSystemPkgBetter) {
8646            // The version of the application on /system is greater than the version on
8647            // /data. Switch back to the application on /system.
8648            // It's safe to assume the application on /system will correctly scan. If not,
8649            // there won't be a working copy of the application.
8650            synchronized (mPackages) {
8651                // just remove the loaded entries from package lists
8652                mPackages.remove(pkgSetting.name);
8653            }
8654
8655            logCriticalInfo(Log.WARN,
8656                    "System package updated;"
8657                    + " name: " + pkgSetting.name
8658                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8659                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8660
8661            final InstallArgs args = createInstallArgsForExisting(
8662                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8663                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8664            args.cleanUpResourcesLI();
8665            synchronized (mPackages) {
8666                mSettings.enableSystemPackageLPw(pkgSetting.name);
8667            }
8668        }
8669
8670        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8671            // The version of the application on the /system partition is less than or
8672            // equal to the version on the /data partition. Throw an exception and use
8673            // the application already installed on the /data partition.
8674            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8675                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8676                    + " better than this " + pkg.getLongVersionCode());
8677        }
8678
8679        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8680        // force re-collecting certificate.
8681        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8682                disabledPkgSetting);
8683        // Full APK verification can be skipped during certificate collection, only if the file is
8684        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8685        // cases, only data in Signing Block is verified instead of the whole file.
8686        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8687                (forceCollect && canSkipFullPackageVerification(pkg));
8688        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8689
8690        boolean shouldHideSystemApp = false;
8691        // A new application appeared on /system, but, we already have a copy of
8692        // the application installed on /data.
8693        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8694                && !pkgSetting.isSystem()) {
8695
8696            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8697                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8698                logCriticalInfo(Log.WARN,
8699                        "System package signature mismatch;"
8700                        + " name: " + pkgSetting.name);
8701                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8702                        "scanPackageInternalLI")) {
8703                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8704                }
8705                pkgSetting = null;
8706            } else if (newPkgVersionGreater) {
8707                // The application on /system is newer than the application on /data.
8708                // Simply remove the application on /data [keeping application data]
8709                // and replace it with the version on /system.
8710                logCriticalInfo(Log.WARN,
8711                        "System package enabled;"
8712                        + " name: " + pkgSetting.name
8713                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8714                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8715                InstallArgs args = createInstallArgsForExisting(
8716                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8717                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8718                synchronized (mInstallLock) {
8719                    args.cleanUpResourcesLI();
8720                }
8721            } else {
8722                // The application on /system is older than the application on /data. Hide
8723                // the application on /system and the version on /data will be scanned later
8724                // and re-added like an update.
8725                shouldHideSystemApp = true;
8726                logCriticalInfo(Log.INFO,
8727                        "System package disabled;"
8728                        + " name: " + pkgSetting.name
8729                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8730                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8731            }
8732        }
8733
8734        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8735                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8736
8737        if (shouldHideSystemApp) {
8738            synchronized (mPackages) {
8739                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8740            }
8741        }
8742        return scannedPkg;
8743    }
8744
8745    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8746        // Derive the new package synthetic package name
8747        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8748                + pkg.staticSharedLibVersion);
8749    }
8750
8751    private static String fixProcessName(String defProcessName,
8752            String processName) {
8753        if (processName == null) {
8754            return defProcessName;
8755        }
8756        return processName;
8757    }
8758
8759    /**
8760     * Enforces that only the system UID or root's UID can call a method exposed
8761     * via Binder.
8762     *
8763     * @param message used as message if SecurityException is thrown
8764     * @throws SecurityException if the caller is not system or root
8765     */
8766    private static final void enforceSystemOrRoot(String message) {
8767        final int uid = Binder.getCallingUid();
8768        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8769            throw new SecurityException(message);
8770        }
8771    }
8772
8773    @Override
8774    public void performFstrimIfNeeded() {
8775        enforceSystemOrRoot("Only the system can request fstrim");
8776
8777        // Before everything else, see whether we need to fstrim.
8778        try {
8779            IStorageManager sm = PackageHelper.getStorageManager();
8780            if (sm != null) {
8781                boolean doTrim = false;
8782                final long interval = android.provider.Settings.Global.getLong(
8783                        mContext.getContentResolver(),
8784                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8785                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8786                if (interval > 0) {
8787                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8788                    if (timeSinceLast > interval) {
8789                        doTrim = true;
8790                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8791                                + "; running immediately");
8792                    }
8793                }
8794                if (doTrim) {
8795                    final boolean dexOptDialogShown;
8796                    synchronized (mPackages) {
8797                        dexOptDialogShown = mDexOptDialogShown;
8798                    }
8799                    if (!isFirstBoot() && dexOptDialogShown) {
8800                        try {
8801                            ActivityManager.getService().showBootMessage(
8802                                    mContext.getResources().getString(
8803                                            R.string.android_upgrading_fstrim), true);
8804                        } catch (RemoteException e) {
8805                        }
8806                    }
8807                    sm.runMaintenance();
8808                }
8809            } else {
8810                Slog.e(TAG, "storageManager service unavailable!");
8811            }
8812        } catch (RemoteException e) {
8813            // Can't happen; StorageManagerService is local
8814        }
8815    }
8816
8817    @Override
8818    public void updatePackagesIfNeeded() {
8819        enforceSystemOrRoot("Only the system can request package update");
8820
8821        // We need to re-extract after an OTA.
8822        boolean causeUpgrade = isUpgrade();
8823
8824        // First boot or factory reset.
8825        // Note: we also handle devices that are upgrading to N right now as if it is their
8826        //       first boot, as they do not have profile data.
8827        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8828
8829        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8830        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8831
8832        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8833            return;
8834        }
8835
8836        List<PackageParser.Package> pkgs;
8837        synchronized (mPackages) {
8838            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8839        }
8840
8841        final long startTime = System.nanoTime();
8842        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8843                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8844                    false /* bootComplete */);
8845
8846        final int elapsedTimeSeconds =
8847                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8848
8849        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8850        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8851        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8852        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8853        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8854    }
8855
8856    /*
8857     * Return the prebuilt profile path given a package base code path.
8858     */
8859    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8860        return pkg.baseCodePath + ".prof";
8861    }
8862
8863    /**
8864     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8865     * containing statistics about the invocation. The array consists of three elements,
8866     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8867     * and {@code numberOfPackagesFailed}.
8868     */
8869    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8870            final String compilerFilter, boolean bootComplete) {
8871
8872        int numberOfPackagesVisited = 0;
8873        int numberOfPackagesOptimized = 0;
8874        int numberOfPackagesSkipped = 0;
8875        int numberOfPackagesFailed = 0;
8876        final int numberOfPackagesToDexopt = pkgs.size();
8877
8878        for (PackageParser.Package pkg : pkgs) {
8879            numberOfPackagesVisited++;
8880
8881            boolean useProfileForDexopt = false;
8882
8883            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8884                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8885                // that are already compiled.
8886                File profileFile = new File(getPrebuildProfilePath(pkg));
8887                // Copy profile if it exists.
8888                if (profileFile.exists()) {
8889                    try {
8890                        // We could also do this lazily before calling dexopt in
8891                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8892                        // is that we don't have a good way to say "do this only once".
8893                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8894                                pkg.applicationInfo.uid, pkg.packageName,
8895                                ArtManager.getProfileName(null))) {
8896                            Log.e(TAG, "Installer failed to copy system profile!");
8897                        } else {
8898                            // Disabled as this causes speed-profile compilation during first boot
8899                            // even if things are already compiled.
8900                            // useProfileForDexopt = true;
8901                        }
8902                    } catch (Exception e) {
8903                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8904                                e);
8905                    }
8906                } else {
8907                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8908                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8909                    // minimize the number off apps being speed-profile compiled during first boot.
8910                    // The other paths will not change the filter.
8911                    if (disabledPs != null && disabledPs.pkg.isStub) {
8912                        // The package is the stub one, remove the stub suffix to get the normal
8913                        // package and APK names.
8914                        String systemProfilePath =
8915                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8916                        profileFile = new File(systemProfilePath);
8917                        // If we have a profile for a compressed APK, copy it to the reference
8918                        // location.
8919                        // Note that copying the profile here will cause it to override the
8920                        // reference profile every OTA even though the existing reference profile
8921                        // may have more data. We can't copy during decompression since the
8922                        // directories are not set up at that point.
8923                        if (profileFile.exists()) {
8924                            try {
8925                                // We could also do this lazily before calling dexopt in
8926                                // PackageDexOptimizer to prevent this happening on first boot. The
8927                                // issue is that we don't have a good way to say "do this only
8928                                // once".
8929                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8930                                        pkg.applicationInfo.uid, pkg.packageName,
8931                                        ArtManager.getProfileName(null))) {
8932                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8933                                } else {
8934                                    useProfileForDexopt = true;
8935                                }
8936                            } catch (Exception e) {
8937                                Log.e(TAG, "Failed to copy profile " +
8938                                        profileFile.getAbsolutePath() + " ", e);
8939                            }
8940                        }
8941                    }
8942                }
8943            }
8944
8945            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8946                if (DEBUG_DEXOPT) {
8947                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8948                }
8949                numberOfPackagesSkipped++;
8950                continue;
8951            }
8952
8953            if (DEBUG_DEXOPT) {
8954                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8955                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8956            }
8957
8958            if (showDialog) {
8959                try {
8960                    ActivityManager.getService().showBootMessage(
8961                            mContext.getResources().getString(R.string.android_upgrading_apk,
8962                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8963                } catch (RemoteException e) {
8964                }
8965                synchronized (mPackages) {
8966                    mDexOptDialogShown = true;
8967                }
8968            }
8969
8970            String pkgCompilerFilter = compilerFilter;
8971            if (useProfileForDexopt) {
8972                // Use background dexopt mode to try and use the profile. Note that this does not
8973                // guarantee usage of the profile.
8974                pkgCompilerFilter =
8975                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
8976                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
8977            }
8978
8979            // checkProfiles is false to avoid merging profiles during boot which
8980            // might interfere with background compilation (b/28612421).
8981            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8982            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8983            // trade-off worth doing to save boot time work.
8984            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8985            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8986                    pkg.packageName,
8987                    pkgCompilerFilter,
8988                    dexoptFlags));
8989
8990            switch (primaryDexOptStaus) {
8991                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8992                    numberOfPackagesOptimized++;
8993                    break;
8994                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8995                    numberOfPackagesSkipped++;
8996                    break;
8997                case PackageDexOptimizer.DEX_OPT_FAILED:
8998                    numberOfPackagesFailed++;
8999                    break;
9000                default:
9001                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9002                    break;
9003            }
9004        }
9005
9006        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9007                numberOfPackagesFailed };
9008    }
9009
9010    @Override
9011    public void notifyPackageUse(String packageName, int reason) {
9012        synchronized (mPackages) {
9013            final int callingUid = Binder.getCallingUid();
9014            final int callingUserId = UserHandle.getUserId(callingUid);
9015            if (getInstantAppPackageName(callingUid) != null) {
9016                if (!isCallerSameApp(packageName, callingUid)) {
9017                    return;
9018                }
9019            } else {
9020                if (isInstantApp(packageName, callingUserId)) {
9021                    return;
9022                }
9023            }
9024            notifyPackageUseLocked(packageName, reason);
9025        }
9026    }
9027
9028    private void notifyPackageUseLocked(String packageName, int reason) {
9029        final PackageParser.Package p = mPackages.get(packageName);
9030        if (p == null) {
9031            return;
9032        }
9033        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9034    }
9035
9036    @Override
9037    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9038            List<String> classPaths, String loaderIsa) {
9039        int userId = UserHandle.getCallingUserId();
9040        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9041        if (ai == null) {
9042            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9043                + loadingPackageName + ", user=" + userId);
9044            return;
9045        }
9046        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9047    }
9048
9049    @Override
9050    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9051            IDexModuleRegisterCallback callback) {
9052        int userId = UserHandle.getCallingUserId();
9053        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9054        DexManager.RegisterDexModuleResult result;
9055        if (ai == null) {
9056            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9057                     " calling user. package=" + packageName + ", user=" + userId);
9058            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9059        } else {
9060            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9061        }
9062
9063        if (callback != null) {
9064            mHandler.post(() -> {
9065                try {
9066                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9067                } catch (RemoteException e) {
9068                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9069                }
9070            });
9071        }
9072    }
9073
9074    /**
9075     * Ask the package manager to perform a dex-opt with the given compiler filter.
9076     *
9077     * Note: exposed only for the shell command to allow moving packages explicitly to a
9078     *       definite state.
9079     */
9080    @Override
9081    public boolean performDexOptMode(String packageName,
9082            boolean checkProfiles, String targetCompilerFilter, boolean force,
9083            boolean bootComplete, String splitName) {
9084        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9085                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9086                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9087        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9088                splitName, flags));
9089    }
9090
9091    /**
9092     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9093     * secondary dex files belonging to the given package.
9094     *
9095     * Note: exposed only for the shell command to allow moving packages explicitly to a
9096     *       definite state.
9097     */
9098    @Override
9099    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9100            boolean force) {
9101        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9102                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9103                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9104                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9105        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9106    }
9107
9108    /*package*/ boolean performDexOpt(DexoptOptions options) {
9109        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9110            return false;
9111        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9112            return false;
9113        }
9114
9115        if (options.isDexoptOnlySecondaryDex()) {
9116            return mDexManager.dexoptSecondaryDex(options);
9117        } else {
9118            int dexoptStatus = performDexOptWithStatus(options);
9119            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9120        }
9121    }
9122
9123    /**
9124     * Perform dexopt on the given package and return one of following result:
9125     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9126     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9127     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9128     */
9129    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9130        return performDexOptTraced(options);
9131    }
9132
9133    private int performDexOptTraced(DexoptOptions options) {
9134        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9135        try {
9136            return performDexOptInternal(options);
9137        } finally {
9138            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9139        }
9140    }
9141
9142    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9143    // if the package can now be considered up to date for the given filter.
9144    private int performDexOptInternal(DexoptOptions options) {
9145        PackageParser.Package p;
9146        synchronized (mPackages) {
9147            p = mPackages.get(options.getPackageName());
9148            if (p == null) {
9149                // Package could not be found. Report failure.
9150                return PackageDexOptimizer.DEX_OPT_FAILED;
9151            }
9152            mPackageUsage.maybeWriteAsync(mPackages);
9153            mCompilerStats.maybeWriteAsync();
9154        }
9155        long callingId = Binder.clearCallingIdentity();
9156        try {
9157            synchronized (mInstallLock) {
9158                return performDexOptInternalWithDependenciesLI(p, options);
9159            }
9160        } finally {
9161            Binder.restoreCallingIdentity(callingId);
9162        }
9163    }
9164
9165    public ArraySet<String> getOptimizablePackages() {
9166        ArraySet<String> pkgs = new ArraySet<String>();
9167        synchronized (mPackages) {
9168            for (PackageParser.Package p : mPackages.values()) {
9169                if (PackageDexOptimizer.canOptimizePackage(p)) {
9170                    pkgs.add(p.packageName);
9171                }
9172            }
9173        }
9174        return pkgs;
9175    }
9176
9177    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9178            DexoptOptions options) {
9179        // Select the dex optimizer based on the force parameter.
9180        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9181        //       allocate an object here.
9182        PackageDexOptimizer pdo = options.isForce()
9183                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9184                : mPackageDexOptimizer;
9185
9186        // Dexopt all dependencies first. Note: we ignore the return value and march on
9187        // on errors.
9188        // Note that we are going to call performDexOpt on those libraries as many times as
9189        // they are referenced in packages. When we do a batch of performDexOpt (for example
9190        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9191        // and the first package that uses the library will dexopt it. The
9192        // others will see that the compiled code for the library is up to date.
9193        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9194        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9195        if (!deps.isEmpty()) {
9196            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9197                    options.getCompilerFilter(), options.getSplitName(),
9198                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9199            for (PackageParser.Package depPackage : deps) {
9200                // TODO: Analyze and investigate if we (should) profile libraries.
9201                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9202                        getOrCreateCompilerPackageStats(depPackage),
9203                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9204            }
9205        }
9206        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9207                getOrCreateCompilerPackageStats(p),
9208                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9209    }
9210
9211    /**
9212     * Reconcile the information we have about the secondary dex files belonging to
9213     * {@code packagName} and the actual dex files. For all dex files that were
9214     * deleted, update the internal records and delete the generated oat files.
9215     */
9216    @Override
9217    public void reconcileSecondaryDexFiles(String packageName) {
9218        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9219            return;
9220        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9221            return;
9222        }
9223        mDexManager.reconcileSecondaryDexFiles(packageName);
9224    }
9225
9226    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9227    // a reference there.
9228    /*package*/ DexManager getDexManager() {
9229        return mDexManager;
9230    }
9231
9232    /**
9233     * Execute the background dexopt job immediately.
9234     */
9235    @Override
9236    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9237        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9238            return false;
9239        }
9240        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9241    }
9242
9243    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9244        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9245                || p.usesStaticLibraries != null) {
9246            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9247            Set<String> collectedNames = new HashSet<>();
9248            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9249
9250            retValue.remove(p);
9251
9252            return retValue;
9253        } else {
9254            return Collections.emptyList();
9255        }
9256    }
9257
9258    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9259            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9260        if (!collectedNames.contains(p.packageName)) {
9261            collectedNames.add(p.packageName);
9262            collected.add(p);
9263
9264            if (p.usesLibraries != null) {
9265                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9266                        null, collected, collectedNames);
9267            }
9268            if (p.usesOptionalLibraries != null) {
9269                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9270                        null, collected, collectedNames);
9271            }
9272            if (p.usesStaticLibraries != null) {
9273                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9274                        p.usesStaticLibrariesVersions, collected, collectedNames);
9275            }
9276        }
9277    }
9278
9279    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9280            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9281        final int libNameCount = libs.size();
9282        for (int i = 0; i < libNameCount; i++) {
9283            String libName = libs.get(i);
9284            long version = (versions != null && versions.length == libNameCount)
9285                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9286            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9287            if (libPkg != null) {
9288                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9289            }
9290        }
9291    }
9292
9293    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9294        synchronized (mPackages) {
9295            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9296            if (libEntry != null) {
9297                return mPackages.get(libEntry.apk);
9298            }
9299            return null;
9300        }
9301    }
9302
9303    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9304        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9305        if (versionedLib == null) {
9306            return null;
9307        }
9308        return versionedLib.get(version);
9309    }
9310
9311    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9312        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9313                pkg.staticSharedLibName);
9314        if (versionedLib == null) {
9315            return null;
9316        }
9317        long previousLibVersion = -1;
9318        final int versionCount = versionedLib.size();
9319        for (int i = 0; i < versionCount; i++) {
9320            final long libVersion = versionedLib.keyAt(i);
9321            if (libVersion < pkg.staticSharedLibVersion) {
9322                previousLibVersion = Math.max(previousLibVersion, libVersion);
9323            }
9324        }
9325        if (previousLibVersion >= 0) {
9326            return versionedLib.get(previousLibVersion);
9327        }
9328        return null;
9329    }
9330
9331    public void shutdown() {
9332        mPackageUsage.writeNow(mPackages);
9333        mCompilerStats.writeNow();
9334        mDexManager.writePackageDexUsageNow();
9335    }
9336
9337    @Override
9338    public void dumpProfiles(String packageName) {
9339        PackageParser.Package pkg;
9340        synchronized (mPackages) {
9341            pkg = mPackages.get(packageName);
9342            if (pkg == null) {
9343                throw new IllegalArgumentException("Unknown package: " + packageName);
9344            }
9345        }
9346        /* Only the shell, root, or the app user should be able to dump profiles. */
9347        int callingUid = Binder.getCallingUid();
9348        if (callingUid != Process.SHELL_UID &&
9349            callingUid != Process.ROOT_UID &&
9350            callingUid != pkg.applicationInfo.uid) {
9351            throw new SecurityException("dumpProfiles");
9352        }
9353
9354        synchronized (mInstallLock) {
9355            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9356            mArtManagerService.dumpProfiles(pkg);
9357            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9358        }
9359    }
9360
9361    @Override
9362    public void forceDexOpt(String packageName) {
9363        enforceSystemOrRoot("forceDexOpt");
9364
9365        PackageParser.Package pkg;
9366        synchronized (mPackages) {
9367            pkg = mPackages.get(packageName);
9368            if (pkg == null) {
9369                throw new IllegalArgumentException("Unknown package: " + packageName);
9370            }
9371        }
9372
9373        synchronized (mInstallLock) {
9374            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9375
9376            // Whoever is calling forceDexOpt wants a compiled package.
9377            // Don't use profiles since that may cause compilation to be skipped.
9378            final int res = performDexOptInternalWithDependenciesLI(
9379                    pkg,
9380                    new DexoptOptions(packageName,
9381                            getDefaultCompilerFilter(),
9382                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9383
9384            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9385            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9386                throw new IllegalStateException("Failed to dexopt: " + res);
9387            }
9388        }
9389    }
9390
9391    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9392        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9393            Slog.w(TAG, "Unable to update from " + oldPkg.name
9394                    + " to " + newPkg.packageName
9395                    + ": old package not in system partition");
9396            return false;
9397        } else if (mPackages.get(oldPkg.name) != null) {
9398            Slog.w(TAG, "Unable to update from " + oldPkg.name
9399                    + " to " + newPkg.packageName
9400                    + ": old package still exists");
9401            return false;
9402        }
9403        return true;
9404    }
9405
9406    void removeCodePathLI(File codePath) {
9407        if (codePath.isDirectory()) {
9408            try {
9409                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9410            } catch (InstallerException e) {
9411                Slog.w(TAG, "Failed to remove code path", e);
9412            }
9413        } else {
9414            codePath.delete();
9415        }
9416    }
9417
9418    private int[] resolveUserIds(int userId) {
9419        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9420    }
9421
9422    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9423        if (pkg == null) {
9424            Slog.wtf(TAG, "Package was null!", new Throwable());
9425            return;
9426        }
9427        clearAppDataLeafLIF(pkg, userId, flags);
9428        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9429        for (int i = 0; i < childCount; i++) {
9430            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9431        }
9432
9433        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9434    }
9435
9436    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9437        final PackageSetting ps;
9438        synchronized (mPackages) {
9439            ps = mSettings.mPackages.get(pkg.packageName);
9440        }
9441        for (int realUserId : resolveUserIds(userId)) {
9442            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9443            try {
9444                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9445                        ceDataInode);
9446            } catch (InstallerException e) {
9447                Slog.w(TAG, String.valueOf(e));
9448            }
9449        }
9450    }
9451
9452    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9453        if (pkg == null) {
9454            Slog.wtf(TAG, "Package was null!", new Throwable());
9455            return;
9456        }
9457        destroyAppDataLeafLIF(pkg, userId, flags);
9458        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9459        for (int i = 0; i < childCount; i++) {
9460            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9461        }
9462    }
9463
9464    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9465        final PackageSetting ps;
9466        synchronized (mPackages) {
9467            ps = mSettings.mPackages.get(pkg.packageName);
9468        }
9469        for (int realUserId : resolveUserIds(userId)) {
9470            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9471            try {
9472                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9473                        ceDataInode);
9474            } catch (InstallerException e) {
9475                Slog.w(TAG, String.valueOf(e));
9476            }
9477            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9478        }
9479    }
9480
9481    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9482        if (pkg == null) {
9483            Slog.wtf(TAG, "Package was null!", new Throwable());
9484            return;
9485        }
9486        destroyAppProfilesLeafLIF(pkg);
9487        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9488        for (int i = 0; i < childCount; i++) {
9489            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9490        }
9491    }
9492
9493    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9494        try {
9495            mInstaller.destroyAppProfiles(pkg.packageName);
9496        } catch (InstallerException e) {
9497            Slog.w(TAG, String.valueOf(e));
9498        }
9499    }
9500
9501    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9502        if (pkg == null) {
9503            Slog.wtf(TAG, "Package was null!", new Throwable());
9504            return;
9505        }
9506        mArtManagerService.clearAppProfiles(pkg);
9507        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9508        for (int i = 0; i < childCount; i++) {
9509            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9510        }
9511    }
9512
9513    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9514            long lastUpdateTime) {
9515        // Set parent install/update time
9516        PackageSetting ps = (PackageSetting) pkg.mExtras;
9517        if (ps != null) {
9518            ps.firstInstallTime = firstInstallTime;
9519            ps.lastUpdateTime = lastUpdateTime;
9520        }
9521        // Set children install/update time
9522        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9523        for (int i = 0; i < childCount; i++) {
9524            PackageParser.Package childPkg = pkg.childPackages.get(i);
9525            ps = (PackageSetting) childPkg.mExtras;
9526            if (ps != null) {
9527                ps.firstInstallTime = firstInstallTime;
9528                ps.lastUpdateTime = lastUpdateTime;
9529            }
9530        }
9531    }
9532
9533    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9534            SharedLibraryEntry file,
9535            PackageParser.Package changingLib) {
9536        if (file.path != null) {
9537            usesLibraryFiles.add(file.path);
9538            return;
9539        }
9540        PackageParser.Package p = mPackages.get(file.apk);
9541        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9542            // If we are doing this while in the middle of updating a library apk,
9543            // then we need to make sure to use that new apk for determining the
9544            // dependencies here.  (We haven't yet finished committing the new apk
9545            // to the package manager state.)
9546            if (p == null || p.packageName.equals(changingLib.packageName)) {
9547                p = changingLib;
9548            }
9549        }
9550        if (p != null) {
9551            usesLibraryFiles.addAll(p.getAllCodePaths());
9552            if (p.usesLibraryFiles != null) {
9553                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9554            }
9555        }
9556    }
9557
9558    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9559            PackageParser.Package changingLib) throws PackageManagerException {
9560        if (pkg == null) {
9561            return;
9562        }
9563        // The collection used here must maintain the order of addition (so
9564        // that libraries are searched in the correct order) and must have no
9565        // duplicates.
9566        Set<String> usesLibraryFiles = null;
9567        if (pkg.usesLibraries != null) {
9568            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9569                    null, null, pkg.packageName, changingLib, true,
9570                    pkg.applicationInfo.targetSdkVersion, null);
9571        }
9572        if (pkg.usesStaticLibraries != null) {
9573            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9574                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9575                    pkg.packageName, changingLib, true,
9576                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9577        }
9578        if (pkg.usesOptionalLibraries != null) {
9579            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9580                    null, null, pkg.packageName, changingLib, false,
9581                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9582        }
9583        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9584            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9585        } else {
9586            pkg.usesLibraryFiles = null;
9587        }
9588    }
9589
9590    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9591            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9592            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9593            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9594            throws PackageManagerException {
9595        final int libCount = requestedLibraries.size();
9596        for (int i = 0; i < libCount; i++) {
9597            final String libName = requestedLibraries.get(i);
9598            final long libVersion = requiredVersions != null ? requiredVersions[i]
9599                    : SharedLibraryInfo.VERSION_UNDEFINED;
9600            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9601            if (libEntry == null) {
9602                if (required) {
9603                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9604                            "Package " + packageName + " requires unavailable shared library "
9605                                    + libName + "; failing!");
9606                } else if (DEBUG_SHARED_LIBRARIES) {
9607                    Slog.i(TAG, "Package " + packageName
9608                            + " desires unavailable shared library "
9609                            + libName + "; ignoring!");
9610                }
9611            } else {
9612                if (requiredVersions != null && requiredCertDigests != null) {
9613                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9614                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9615                            "Package " + packageName + " requires unavailable static shared"
9616                                    + " library " + libName + " version "
9617                                    + libEntry.info.getLongVersion() + "; failing!");
9618                    }
9619
9620                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9621                    if (libPkg == null) {
9622                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9623                                "Package " + packageName + " requires unavailable static shared"
9624                                        + " library; failing!");
9625                    }
9626
9627                    final String[] expectedCertDigests = requiredCertDigests[i];
9628
9629
9630                    if (expectedCertDigests.length > 1) {
9631
9632                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9633                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9634                                ? PackageUtils.computeSignaturesSha256Digests(
9635                                libPkg.mSigningDetails.signatures)
9636                                : PackageUtils.computeSignaturesSha256Digests(
9637                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9638
9639                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9640                        // target O we don't parse the "additional-certificate" tags similarly
9641                        // how we only consider all certs only for apps targeting O (see above).
9642                        // Therefore, the size check is safe to make.
9643                        if (expectedCertDigests.length != libCertDigests.length) {
9644                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9645                                    "Package " + packageName + " requires differently signed" +
9646                                            " static shared library; failing!");
9647                        }
9648
9649                        // Use a predictable order as signature order may vary
9650                        Arrays.sort(libCertDigests);
9651                        Arrays.sort(expectedCertDigests);
9652
9653                        final int certCount = libCertDigests.length;
9654                        for (int j = 0; j < certCount; j++) {
9655                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9656                                throw new PackageManagerException(
9657                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9658                                        "Package " + packageName + " requires differently signed" +
9659                                                " static shared library; failing!");
9660                            }
9661                        }
9662                    } else {
9663
9664                        // lib signing cert could have rotated beyond the one expected, check to see
9665                        // if the new one has been blessed by the old
9666                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9667                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9668                            throw new PackageManagerException(
9669                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9670                                    "Package " + packageName + " requires differently signed" +
9671                                            " static shared library; failing!");
9672                        }
9673                    }
9674                }
9675
9676                if (outUsedLibraries == null) {
9677                    // Use LinkedHashSet to preserve the order of files added to
9678                    // usesLibraryFiles while eliminating duplicates.
9679                    outUsedLibraries = new LinkedHashSet<>();
9680                }
9681                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9682            }
9683        }
9684        return outUsedLibraries;
9685    }
9686
9687    private static boolean hasString(List<String> list, List<String> which) {
9688        if (list == null) {
9689            return false;
9690        }
9691        for (int i=list.size()-1; i>=0; i--) {
9692            for (int j=which.size()-1; j>=0; j--) {
9693                if (which.get(j).equals(list.get(i))) {
9694                    return true;
9695                }
9696            }
9697        }
9698        return false;
9699    }
9700
9701    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9702            PackageParser.Package changingPkg) {
9703        ArrayList<PackageParser.Package> res = null;
9704        for (PackageParser.Package pkg : mPackages.values()) {
9705            if (changingPkg != null
9706                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9707                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9708                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9709                            changingPkg.staticSharedLibName)) {
9710                return null;
9711            }
9712            if (res == null) {
9713                res = new ArrayList<>();
9714            }
9715            res.add(pkg);
9716            try {
9717                updateSharedLibrariesLPr(pkg, changingPkg);
9718            } catch (PackageManagerException e) {
9719                // If a system app update or an app and a required lib missing we
9720                // delete the package and for updated system apps keep the data as
9721                // it is better for the user to reinstall than to be in an limbo
9722                // state. Also libs disappearing under an app should never happen
9723                // - just in case.
9724                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9725                    final int flags = pkg.isUpdatedSystemApp()
9726                            ? PackageManager.DELETE_KEEP_DATA : 0;
9727                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9728                            flags , null, true, null);
9729                }
9730                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9731            }
9732        }
9733        return res;
9734    }
9735
9736    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9737            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9738            @Nullable UserHandle user) throws PackageManagerException {
9739        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9740        // If the package has children and this is the first dive in the function
9741        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9742        // whether all packages (parent and children) would be successfully scanned
9743        // before the actual scan since scanning mutates internal state and we want
9744        // to atomically install the package and its children.
9745        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9746            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9747                scanFlags |= SCAN_CHECK_ONLY;
9748            }
9749        } else {
9750            scanFlags &= ~SCAN_CHECK_ONLY;
9751        }
9752
9753        final PackageParser.Package scannedPkg;
9754        try {
9755            // Scan the parent
9756            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9757            // Scan the children
9758            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9759            for (int i = 0; i < childCount; i++) {
9760                PackageParser.Package childPkg = pkg.childPackages.get(i);
9761                scanPackageNewLI(childPkg, parseFlags,
9762                        scanFlags, currentTime, user);
9763            }
9764        } finally {
9765            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9766        }
9767
9768        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9769            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9770        }
9771
9772        return scannedPkg;
9773    }
9774
9775    /** The result of a package scan. */
9776    private static class ScanResult {
9777        /** Whether or not the package scan was successful */
9778        public final boolean success;
9779        /**
9780         * The final package settings. This may be the same object passed in
9781         * the {@link ScanRequest}, but, with modified values.
9782         */
9783        @Nullable public final PackageSetting pkgSetting;
9784        /** ABI code paths that have changed in the package scan */
9785        @Nullable public final List<String> changedAbiCodePath;
9786        public ScanResult(
9787                boolean success,
9788                @Nullable PackageSetting pkgSetting,
9789                @Nullable List<String> changedAbiCodePath) {
9790            this.success = success;
9791            this.pkgSetting = pkgSetting;
9792            this.changedAbiCodePath = changedAbiCodePath;
9793        }
9794    }
9795
9796    /** A package to be scanned */
9797    private static class ScanRequest {
9798        /** The parsed package */
9799        @NonNull public final PackageParser.Package pkg;
9800        /** Shared user settings, if the package has a shared user */
9801        @Nullable public final SharedUserSetting sharedUserSetting;
9802        /**
9803         * Package settings of the currently installed version.
9804         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9805         * during scan.
9806         */
9807        @Nullable public final PackageSetting pkgSetting;
9808        /** A copy of the settings for the currently installed version */
9809        @Nullable public final PackageSetting oldPkgSetting;
9810        /** Package settings for the disabled version on the /system partition */
9811        @Nullable public final PackageSetting disabledPkgSetting;
9812        /** Package settings for the installed version under its original package name */
9813        @Nullable public final PackageSetting originalPkgSetting;
9814        /** The real package name of a renamed application */
9815        @Nullable public final String realPkgName;
9816        public final @ParseFlags int parseFlags;
9817        public final @ScanFlags int scanFlags;
9818        /** The user for which the package is being scanned */
9819        @Nullable public final UserHandle user;
9820        /** Whether or not the platform package is being scanned */
9821        public final boolean isPlatformPackage;
9822        public ScanRequest(
9823                @NonNull PackageParser.Package pkg,
9824                @Nullable SharedUserSetting sharedUserSetting,
9825                @Nullable PackageSetting pkgSetting,
9826                @Nullable PackageSetting disabledPkgSetting,
9827                @Nullable PackageSetting originalPkgSetting,
9828                @Nullable String realPkgName,
9829                @ParseFlags int parseFlags,
9830                @ScanFlags int scanFlags,
9831                boolean isPlatformPackage,
9832                @Nullable UserHandle user) {
9833            this.pkg = pkg;
9834            this.pkgSetting = pkgSetting;
9835            this.sharedUserSetting = sharedUserSetting;
9836            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9837            this.disabledPkgSetting = disabledPkgSetting;
9838            this.originalPkgSetting = originalPkgSetting;
9839            this.realPkgName = realPkgName;
9840            this.parseFlags = parseFlags;
9841            this.scanFlags = scanFlags;
9842            this.isPlatformPackage = isPlatformPackage;
9843            this.user = user;
9844        }
9845    }
9846
9847    /**
9848     * Returns the actual scan flags depending upon the state of the other settings.
9849     * <p>Updated system applications will not have the following flags set
9850     * by default and need to be adjusted after the fact:
9851     * <ul>
9852     * <li>{@link #SCAN_AS_SYSTEM}</li>
9853     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9854     * <li>{@link #SCAN_AS_OEM}</li>
9855     * <li>{@link #SCAN_AS_VENDOR}</li>
9856     * <li>{@link #SCAN_AS_PRODUCT}</li>
9857     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9858     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9859     * </ul>
9860     */
9861    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9862            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9863            PackageParser.Package pkg) {
9864        if (disabledPkgSetting != null) {
9865            // updated system application, must at least have SCAN_AS_SYSTEM
9866            scanFlags |= SCAN_AS_SYSTEM;
9867            if ((disabledPkgSetting.pkgPrivateFlags
9868                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9869                scanFlags |= SCAN_AS_PRIVILEGED;
9870            }
9871            if ((disabledPkgSetting.pkgPrivateFlags
9872                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9873                scanFlags |= SCAN_AS_OEM;
9874            }
9875            if ((disabledPkgSetting.pkgPrivateFlags
9876                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9877                scanFlags |= SCAN_AS_VENDOR;
9878            }
9879            if ((disabledPkgSetting.pkgPrivateFlags
9880                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9881                scanFlags |= SCAN_AS_PRODUCT;
9882            }
9883        }
9884        if (pkgSetting != null) {
9885            final int userId = ((user == null) ? 0 : user.getIdentifier());
9886            if (pkgSetting.getInstantApp(userId)) {
9887                scanFlags |= SCAN_AS_INSTANT_APP;
9888            }
9889            if (pkgSetting.getVirtulalPreload(userId)) {
9890                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9891            }
9892        }
9893
9894        // Scan as privileged apps that share a user with a priv-app.
9895        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9896                && (pkg.mSharedUserId != null)) {
9897            SharedUserSetting sharedUserSetting = null;
9898            try {
9899                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9900            } catch (PackageManagerException ignore) {}
9901            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9902                // Exempt SharedUsers signed with the platform key.
9903                // TODO(b/72378145) Fix this exemption. Force signature apps
9904                // to whitelist their privileged permissions just like other
9905                // priv-apps.
9906                synchronized (mPackages) {
9907                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9908                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9909                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9910                        scanFlags |= SCAN_AS_PRIVILEGED;
9911                    }
9912                }
9913            }
9914        }
9915
9916        return scanFlags;
9917    }
9918
9919    @GuardedBy("mInstallLock")
9920    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9921            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9922            @Nullable UserHandle user) throws PackageManagerException {
9923
9924        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9925        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9926        if (realPkgName != null) {
9927            ensurePackageRenamed(pkg, renamedPkgName);
9928        }
9929        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9930        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9931        final PackageSetting disabledPkgSetting =
9932                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9933
9934        if (mTransferedPackages.contains(pkg.packageName)) {
9935            Slog.w(TAG, "Package " + pkg.packageName
9936                    + " was transferred to another, but its .apk remains");
9937        }
9938
9939        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
9940        synchronized (mPackages) {
9941            applyPolicy(pkg, parseFlags, scanFlags);
9942            assertPackageIsValid(pkg, parseFlags, scanFlags);
9943
9944            SharedUserSetting sharedUserSetting = null;
9945            if (pkg.mSharedUserId != null) {
9946                // SIDE EFFECTS; may potentially allocate a new shared user
9947                sharedUserSetting = mSettings.getSharedUserLPw(
9948                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9949                if (DEBUG_PACKAGE_SCANNING) {
9950                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9951                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
9952                                + " (uid=" + sharedUserSetting.userId + "):"
9953                                + " packages=" + sharedUserSetting.packages);
9954                }
9955            }
9956
9957            boolean scanSucceeded = false;
9958            try {
9959                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
9960                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
9961                        (pkg == mPlatformPackage), user);
9962                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
9963                if (result.success) {
9964                    commitScanResultsLocked(request, result);
9965                }
9966                scanSucceeded = true;
9967            } finally {
9968                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9969                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
9970                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9971                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9972                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9973                  }
9974            }
9975        }
9976        return pkg;
9977    }
9978
9979    /**
9980     * Commits the package scan and modifies system state.
9981     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
9982     * of committing the package, leaving the system in an inconsistent state.
9983     * This needs to be fixed so, once we get to this point, no errors are
9984     * possible and the system is not left in an inconsistent state.
9985     */
9986    @GuardedBy("mPackages")
9987    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
9988            throws PackageManagerException {
9989        final PackageParser.Package pkg = request.pkg;
9990        final @ParseFlags int parseFlags = request.parseFlags;
9991        final @ScanFlags int scanFlags = request.scanFlags;
9992        final PackageSetting oldPkgSetting = request.oldPkgSetting;
9993        final PackageSetting originalPkgSetting = request.originalPkgSetting;
9994        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
9995        final UserHandle user = request.user;
9996        final String realPkgName = request.realPkgName;
9997        final PackageSetting pkgSetting = result.pkgSetting;
9998        final List<String> changedAbiCodePath = result.changedAbiCodePath;
9999        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10000
10001        if (newPkgSettingCreated) {
10002            if (originalPkgSetting != null) {
10003                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10004            }
10005            // THROWS: when we can't allocate a user id. add call to check if there's
10006            // enough space to ensure we won't throw; otherwise, don't modify state
10007            mSettings.addUserToSettingLPw(pkgSetting);
10008
10009            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10010                mTransferedPackages.add(originalPkgSetting.name);
10011            }
10012        }
10013        // TODO(toddke): Consider a method specifically for modifying the Package object
10014        // post scan; or, moving this stuff out of the Package object since it has nothing
10015        // to do with the package on disk.
10016        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10017        // for creating the application ID. If we did this earlier, we would be saving the
10018        // correct ID.
10019        pkg.applicationInfo.uid = pkgSetting.appId;
10020
10021        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10022
10023        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10024            mTransferedPackages.add(pkg.packageName);
10025        }
10026
10027        // THROWS: when requested libraries that can't be found. it only changes
10028        // the state of the passed in pkg object, so, move to the top of the method
10029        // and allow it to abort
10030        if ((scanFlags & SCAN_BOOTING) == 0
10031                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10032            // Check all shared libraries and map to their actual file path.
10033            // We only do this here for apps not on a system dir, because those
10034            // are the only ones that can fail an install due to this.  We
10035            // will take care of the system apps by updating all of their
10036            // library paths after the scan is done. Also during the initial
10037            // scan don't update any libs as we do this wholesale after all
10038            // apps are scanned to avoid dependency based scanning.
10039            updateSharedLibrariesLPr(pkg, null);
10040        }
10041
10042        // All versions of a static shared library are referenced with the same
10043        // package name. Internally, we use a synthetic package name to allow
10044        // multiple versions of the same shared library to be installed. So,
10045        // we need to generate the synthetic package name of the latest shared
10046        // library in order to compare signatures.
10047        PackageSetting signatureCheckPs = pkgSetting;
10048        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10049            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10050            if (libraryEntry != null) {
10051                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10052            }
10053        }
10054
10055        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10056        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10057            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10058                // We just determined the app is signed correctly, so bring
10059                // over the latest parsed certs.
10060                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10061            } else {
10062                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10063                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10064                            "Package " + pkg.packageName + " upgrade keys do not match the "
10065                                    + "previously installed version");
10066                } else {
10067                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10068                    String msg = "System package " + pkg.packageName
10069                            + " signature changed; retaining data.";
10070                    reportSettingsProblem(Log.WARN, msg);
10071                }
10072            }
10073        } else {
10074            try {
10075                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10076                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10077                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10078                        pkg.mSigningDetails, compareCompat, compareRecover);
10079                // The new KeySets will be re-added later in the scanning process.
10080                if (compatMatch) {
10081                    synchronized (mPackages) {
10082                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10083                    }
10084                }
10085                // We just determined the app is signed correctly, so bring
10086                // over the latest parsed certs.
10087                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10088
10089
10090                // if this is is a sharedUser, check to see if the new package is signed by a newer
10091                // signing certificate than the existing one, and if so, copy over the new details
10092                if (signatureCheckPs.sharedUser != null
10093                        && pkg.mSigningDetails.hasAncestor(
10094                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10095                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10096                }
10097            } catch (PackageManagerException e) {
10098                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10099                    throw e;
10100                }
10101                // The signature has changed, but this package is in the system
10102                // image...  let's recover!
10103                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10104                // However...  if this package is part of a shared user, but it
10105                // doesn't match the signature of the shared user, let's fail.
10106                // What this means is that you can't change the signatures
10107                // associated with an overall shared user, which doesn't seem all
10108                // that unreasonable.
10109                if (signatureCheckPs.sharedUser != null) {
10110                    if (compareSignatures(
10111                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10112                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10113                        throw new PackageManagerException(
10114                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10115                                "Signature mismatch for shared user: "
10116                                        + pkgSetting.sharedUser);
10117                    }
10118                }
10119                // File a report about this.
10120                String msg = "System package " + pkg.packageName
10121                        + " signature changed; retaining data.";
10122                reportSettingsProblem(Log.WARN, msg);
10123            } catch (IllegalArgumentException e) {
10124
10125                // should never happen: certs matched when checking, but not when comparing
10126                // old to new for sharedUser
10127                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10128                        "Signing certificates comparison made on incomparable signing details"
10129                        + " but somehow passed verifySignatures!");
10130            }
10131        }
10132
10133        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10134            // This package wants to adopt ownership of permissions from
10135            // another package.
10136            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10137                final String origName = pkg.mAdoptPermissions.get(i);
10138                final PackageSetting orig = mSettings.getPackageLPr(origName);
10139                if (orig != null) {
10140                    if (verifyPackageUpdateLPr(orig, pkg)) {
10141                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10142                                + pkg.packageName);
10143                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10144                    }
10145                }
10146            }
10147        }
10148
10149        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10150            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10151                final String codePathString = changedAbiCodePath.get(i);
10152                try {
10153                    mInstaller.rmdex(codePathString,
10154                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10155                } catch (InstallerException ignored) {
10156                }
10157            }
10158        }
10159
10160        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10161            if (oldPkgSetting != null) {
10162                synchronized (mPackages) {
10163                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10164                }
10165            }
10166        } else {
10167            final int userId = user == null ? 0 : user.getIdentifier();
10168            // Modify state for the given package setting
10169            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10170                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10171            if (pkgSetting.getInstantApp(userId)) {
10172                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10173            }
10174        }
10175    }
10176
10177    /**
10178     * Returns the "real" name of the package.
10179     * <p>This may differ from the package's actual name if the application has already
10180     * been installed under one of this package's original names.
10181     */
10182    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10183            @Nullable String renamedPkgName) {
10184        if (isPackageRenamed(pkg, renamedPkgName)) {
10185            return pkg.mRealPackage;
10186        }
10187        return null;
10188    }
10189
10190    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10191    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10192            @Nullable String renamedPkgName) {
10193        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10194    }
10195
10196    /**
10197     * Returns the original package setting.
10198     * <p>A package can migrate its name during an update. In this scenario, a package
10199     * designates a set of names that it considers as one of its original names.
10200     * <p>An original package must be signed identically and it must have the same
10201     * shared user [if any].
10202     */
10203    @GuardedBy("mPackages")
10204    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10205            @Nullable String renamedPkgName) {
10206        if (!isPackageRenamed(pkg, renamedPkgName)) {
10207            return null;
10208        }
10209        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10210            final PackageSetting originalPs =
10211                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10212            if (originalPs != null) {
10213                // the package is already installed under its original name...
10214                // but, should we use it?
10215                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10216                    // the new package is incompatible with the original
10217                    continue;
10218                } else if (originalPs.sharedUser != null) {
10219                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10220                        // the shared user id is incompatible with the original
10221                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10222                                + " to " + pkg.packageName + ": old uid "
10223                                + originalPs.sharedUser.name
10224                                + " differs from " + pkg.mSharedUserId);
10225                        continue;
10226                    }
10227                    // TODO: Add case when shared user id is added [b/28144775]
10228                } else {
10229                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10230                            + pkg.packageName + " to old name " + originalPs.name);
10231                }
10232                return originalPs;
10233            }
10234        }
10235        return null;
10236    }
10237
10238    /**
10239     * Renames the package if it was installed under a different name.
10240     * <p>When we've already installed the package under an original name, update
10241     * the new package so we can continue to have the old name.
10242     */
10243    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10244            @NonNull String renamedPackageName) {
10245        if (pkg.mOriginalPackages == null
10246                || !pkg.mOriginalPackages.contains(renamedPackageName)
10247                || pkg.packageName.equals(renamedPackageName)) {
10248            return;
10249        }
10250        pkg.setPackageName(renamedPackageName);
10251    }
10252
10253    /**
10254     * Just scans the package without any side effects.
10255     * <p>Not entirely true at the moment. There is still one side effect -- this
10256     * method potentially modifies a live {@link PackageSetting} object representing
10257     * the package being scanned. This will be resolved in the future.
10258     *
10259     * @param request Information about the package to be scanned
10260     * @param isUnderFactoryTest Whether or not the device is under factory test
10261     * @param currentTime The current time, in millis
10262     * @return The results of the scan
10263     */
10264    @GuardedBy("mInstallLock")
10265    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10266            boolean isUnderFactoryTest, long currentTime)
10267                    throws PackageManagerException {
10268        final PackageParser.Package pkg = request.pkg;
10269        PackageSetting pkgSetting = request.pkgSetting;
10270        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10271        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10272        final @ParseFlags int parseFlags = request.parseFlags;
10273        final @ScanFlags int scanFlags = request.scanFlags;
10274        final String realPkgName = request.realPkgName;
10275        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10276        final UserHandle user = request.user;
10277        final boolean isPlatformPackage = request.isPlatformPackage;
10278
10279        List<String> changedAbiCodePath = null;
10280
10281        if (DEBUG_PACKAGE_SCANNING) {
10282            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10283                Log.d(TAG, "Scanning package " + pkg.packageName);
10284        }
10285
10286        if (Build.IS_DEBUGGABLE &&
10287                pkg.isPrivileged() &&
10288                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10289            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10290        }
10291
10292        // Initialize package source and resource directories
10293        final File scanFile = new File(pkg.codePath);
10294        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10295        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10296
10297        // We keep references to the derived CPU Abis from settings in oder to reuse
10298        // them in the case where we're not upgrading or booting for the first time.
10299        String primaryCpuAbiFromSettings = null;
10300        String secondaryCpuAbiFromSettings = null;
10301        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10302
10303        if (!needToDeriveAbi) {
10304            if (pkgSetting != null) {
10305                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10306                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10307            } else {
10308                // Re-scanning a system package after uninstalling updates; need to derive ABI
10309                needToDeriveAbi = true;
10310            }
10311        }
10312
10313        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10314            PackageManagerService.reportSettingsProblem(Log.WARN,
10315                    "Package " + pkg.packageName + " shared user changed from "
10316                            + (pkgSetting.sharedUser != null
10317                            ? pkgSetting.sharedUser.name : "<nothing>")
10318                            + " to "
10319                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10320                            + "; replacing with new");
10321            pkgSetting = null;
10322        }
10323
10324        String[] usesStaticLibraries = null;
10325        if (pkg.usesStaticLibraries != null) {
10326            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10327            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10328        }
10329        final boolean createNewPackage = (pkgSetting == null);
10330        if (createNewPackage) {
10331            final String parentPackageName = (pkg.parentPackage != null)
10332                    ? pkg.parentPackage.packageName : null;
10333            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10334            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10335            // REMOVE SharedUserSetting from method; update in a separate call
10336            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10337                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10338                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10339                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10340                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10341                    user, true /*allowInstall*/, instantApp, virtualPreload,
10342                    parentPackageName, pkg.getChildPackageNames(),
10343                    UserManagerService.getInstance(), usesStaticLibraries,
10344                    pkg.usesStaticLibrariesVersions);
10345        } else {
10346            // REMOVE SharedUserSetting from method; update in a separate call.
10347            //
10348            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10349            // secondaryCpuAbi are not known at this point so we always update them
10350            // to null here, only to reset them at a later point.
10351            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10352                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10353                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10354                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10355                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10356                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10357        }
10358        if (createNewPackage && originalPkgSetting != null) {
10359            // This is the initial transition from the original package, so,
10360            // fix up the new package's name now. We must do this after looking
10361            // up the package under its new name, so getPackageLP takes care of
10362            // fiddling things correctly.
10363            pkg.setPackageName(originalPkgSetting.name);
10364
10365            // File a report about this.
10366            String msg = "New package " + pkgSetting.realName
10367                    + " renamed to replace old package " + pkgSetting.name;
10368            reportSettingsProblem(Log.WARN, msg);
10369        }
10370
10371        if (disabledPkgSetting != null) {
10372            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10373        }
10374
10375        // SELinux sandboxes become more restrictive as targetSdkVersion increases.
10376        // To ensure that apps with sharedUserId are placed in the same selinux domain
10377        // without breaking any assumptions about access, put them into the least
10378        // restrictive targetSdkVersion=25 domain.
10379        // TODO(b/72290969): Base this on the actual targetSdkVersion(s) of the apps within the
10380        // sharedUserSetting, instead of defaulting to the least restrictive domain.
10381        final int targetSdk = (sharedUserSetting != null) ? 25
10382                : pkg.applicationInfo.targetSdkVersion;
10383        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10384        // They currently can be if the sharedUser apps are signed with the platform key.
10385        final boolean isPrivileged = (sharedUserSetting != null) ?
10386            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10387
10388        SELinuxMMAC.assignSeInfoValue(pkg, isPrivileged, targetSdk);
10389
10390        pkg.mExtras = pkgSetting;
10391        pkg.applicationInfo.processName = fixProcessName(
10392                pkg.applicationInfo.packageName,
10393                pkg.applicationInfo.processName);
10394
10395        if (!isPlatformPackage) {
10396            // Get all of our default paths setup
10397            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10398        }
10399
10400        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10401
10402        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10403            if (needToDeriveAbi) {
10404                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10405                final boolean extractNativeLibs = !pkg.isLibrary();
10406                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10407                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10408
10409                // Some system apps still use directory structure for native libraries
10410                // in which case we might end up not detecting abi solely based on apk
10411                // structure. Try to detect abi based on directory structure.
10412                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10413                        pkg.applicationInfo.primaryCpuAbi == null) {
10414                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10415                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10416                }
10417            } else {
10418                // This is not a first boot or an upgrade, don't bother deriving the
10419                // ABI during the scan. Instead, trust the value that was stored in the
10420                // package setting.
10421                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10422                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10423
10424                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10425
10426                if (DEBUG_ABI_SELECTION) {
10427                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10428                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10429                            pkg.applicationInfo.secondaryCpuAbi);
10430                }
10431            }
10432        } else {
10433            if ((scanFlags & SCAN_MOVE) != 0) {
10434                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10435                // but we already have this packages package info in the PackageSetting. We just
10436                // use that and derive the native library path based on the new codepath.
10437                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10438                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10439            }
10440
10441            // Set native library paths again. For moves, the path will be updated based on the
10442            // ABIs we've determined above. For non-moves, the path will be updated based on the
10443            // ABIs we determined during compilation, but the path will depend on the final
10444            // package path (after the rename away from the stage path).
10445            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10446        }
10447
10448        // This is a special case for the "system" package, where the ABI is
10449        // dictated by the zygote configuration (and init.rc). We should keep track
10450        // of this ABI so that we can deal with "normal" applications that run under
10451        // the same UID correctly.
10452        if (isPlatformPackage) {
10453            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10454                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10455        }
10456
10457        // If there's a mismatch between the abi-override in the package setting
10458        // and the abiOverride specified for the install. Warn about this because we
10459        // would've already compiled the app without taking the package setting into
10460        // account.
10461        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10462            if (cpuAbiOverride == null && pkg.packageName != null) {
10463                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10464                        " for package " + pkg.packageName);
10465            }
10466        }
10467
10468        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10469        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10470        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10471
10472        // Copy the derived override back to the parsed package, so that we can
10473        // update the package settings accordingly.
10474        pkg.cpuAbiOverride = cpuAbiOverride;
10475
10476        if (DEBUG_ABI_SELECTION) {
10477            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10478                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10479                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10480        }
10481
10482        // Push the derived path down into PackageSettings so we know what to
10483        // clean up at uninstall time.
10484        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10485
10486        if (DEBUG_ABI_SELECTION) {
10487            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10488                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10489                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10490        }
10491
10492        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10493            // We don't do this here during boot because we can do it all
10494            // at once after scanning all existing packages.
10495            //
10496            // We also do this *before* we perform dexopt on this package, so that
10497            // we can avoid redundant dexopts, and also to make sure we've got the
10498            // code and package path correct.
10499            changedAbiCodePath =
10500                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10501        }
10502
10503        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10504                android.Manifest.permission.FACTORY_TEST)) {
10505            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10506        }
10507
10508        if (isSystemApp(pkg)) {
10509            pkgSetting.isOrphaned = true;
10510        }
10511
10512        // Take care of first install / last update times.
10513        final long scanFileTime = getLastModifiedTime(pkg);
10514        if (currentTime != 0) {
10515            if (pkgSetting.firstInstallTime == 0) {
10516                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10517            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10518                pkgSetting.lastUpdateTime = currentTime;
10519            }
10520        } else if (pkgSetting.firstInstallTime == 0) {
10521            // We need *something*.  Take time time stamp of the file.
10522            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10523        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10524            if (scanFileTime != pkgSetting.timeStamp) {
10525                // A package on the system image has changed; consider this
10526                // to be an update.
10527                pkgSetting.lastUpdateTime = scanFileTime;
10528            }
10529        }
10530        pkgSetting.setTimeStamp(scanFileTime);
10531
10532        pkgSetting.pkg = pkg;
10533        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10534        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10535            pkgSetting.versionCode = pkg.getLongVersionCode();
10536        }
10537        // Update volume if needed
10538        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10539        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10540            Slog.i(PackageManagerService.TAG,
10541                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10542                    + " package " + pkg.packageName
10543                    + " volume from " + pkgSetting.volumeUuid
10544                    + " to " + volumeUuid);
10545            pkgSetting.volumeUuid = volumeUuid;
10546        }
10547
10548        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10549    }
10550
10551    /**
10552     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10553     */
10554    private static boolean apkHasCode(String fileName) {
10555        StrictJarFile jarFile = null;
10556        try {
10557            jarFile = new StrictJarFile(fileName,
10558                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10559            return jarFile.findEntry("classes.dex") != null;
10560        } catch (IOException ignore) {
10561        } finally {
10562            try {
10563                if (jarFile != null) {
10564                    jarFile.close();
10565                }
10566            } catch (IOException ignore) {}
10567        }
10568        return false;
10569    }
10570
10571    /**
10572     * Enforces code policy for the package. This ensures that if an APK has
10573     * declared hasCode="true" in its manifest that the APK actually contains
10574     * code.
10575     *
10576     * @throws PackageManagerException If bytecode could not be found when it should exist
10577     */
10578    private static void assertCodePolicy(PackageParser.Package pkg)
10579            throws PackageManagerException {
10580        final boolean shouldHaveCode =
10581                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10582        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10583            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10584                    "Package " + pkg.baseCodePath + " code is missing");
10585        }
10586
10587        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10588            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10589                final boolean splitShouldHaveCode =
10590                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10591                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10592                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10593                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10594                }
10595            }
10596        }
10597    }
10598
10599    /**
10600     * Applies policy to the parsed package based upon the given policy flags.
10601     * Ensures the package is in a good state.
10602     * <p>
10603     * Implementation detail: This method must NOT have any side effect. It would
10604     * ideally be static, but, it requires locks to read system state.
10605     */
10606    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10607            final @ScanFlags int scanFlags) {
10608        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10609            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10610            if (pkg.applicationInfo.isDirectBootAware()) {
10611                // we're direct boot aware; set for all components
10612                for (PackageParser.Service s : pkg.services) {
10613                    s.info.encryptionAware = s.info.directBootAware = true;
10614                }
10615                for (PackageParser.Provider p : pkg.providers) {
10616                    p.info.encryptionAware = p.info.directBootAware = true;
10617                }
10618                for (PackageParser.Activity a : pkg.activities) {
10619                    a.info.encryptionAware = a.info.directBootAware = true;
10620                }
10621                for (PackageParser.Activity r : pkg.receivers) {
10622                    r.info.encryptionAware = r.info.directBootAware = true;
10623                }
10624            }
10625            if (compressedFileExists(pkg.codePath)) {
10626                pkg.isStub = true;
10627            }
10628        } else {
10629            // non system apps can't be flagged as core
10630            pkg.coreApp = false;
10631            // clear flags not applicable to regular apps
10632            pkg.applicationInfo.flags &=
10633                    ~ApplicationInfo.FLAG_PERSISTENT;
10634            pkg.applicationInfo.privateFlags &=
10635                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10636            pkg.applicationInfo.privateFlags &=
10637                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10638            // cap permission priorities
10639            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10640                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10641                    pkg.permissionGroups.get(i).info.priority = 0;
10642                }
10643            }
10644        }
10645        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10646            // clear protected broadcasts
10647            pkg.protectedBroadcasts = null;
10648            // ignore export request for single user receivers
10649            if (pkg.receivers != null) {
10650                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10651                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10652                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10653                        receiver.info.exported = false;
10654                    }
10655                }
10656            }
10657            // ignore export request for single user services
10658            if (pkg.services != null) {
10659                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10660                    final PackageParser.Service service = pkg.services.get(i);
10661                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10662                        service.info.exported = false;
10663                    }
10664                }
10665            }
10666            // ignore export request for single user providers
10667            if (pkg.providers != null) {
10668                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10669                    final PackageParser.Provider provider = pkg.providers.get(i);
10670                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10671                        provider.info.exported = false;
10672                    }
10673                }
10674            }
10675        }
10676
10677        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10678            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10679        }
10680
10681        if ((scanFlags & SCAN_AS_OEM) != 0) {
10682            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10683        }
10684
10685        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10686            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10687        }
10688
10689        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10690            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10691        }
10692
10693        if (!isSystemApp(pkg)) {
10694            // Only system apps can use these features.
10695            pkg.mOriginalPackages = null;
10696            pkg.mRealPackage = null;
10697            pkg.mAdoptPermissions = null;
10698        }
10699    }
10700
10701    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10702            throws PackageManagerException {
10703        if (object == null) {
10704            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10705        }
10706        return object;
10707    }
10708
10709    /**
10710     * Asserts the parsed package is valid according to the given policy. If the
10711     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10712     * <p>
10713     * Implementation detail: This method must NOT have any side effects. It would
10714     * ideally be static, but, it requires locks to read system state.
10715     *
10716     * @throws PackageManagerException If the package fails any of the validation checks
10717     */
10718    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10719            final @ScanFlags int scanFlags)
10720                    throws PackageManagerException {
10721        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10722            assertCodePolicy(pkg);
10723        }
10724
10725        if (pkg.applicationInfo.getCodePath() == null ||
10726                pkg.applicationInfo.getResourcePath() == null) {
10727            // Bail out. The resource and code paths haven't been set.
10728            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10729                    "Code and resource paths haven't been set correctly");
10730        }
10731
10732        // Make sure we're not adding any bogus keyset info
10733        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10734        ksms.assertScannedPackageValid(pkg);
10735
10736        synchronized (mPackages) {
10737            // The special "android" package can only be defined once
10738            if (pkg.packageName.equals("android")) {
10739                if (mAndroidApplication != null) {
10740                    Slog.w(TAG, "*************************************************");
10741                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10742                    Slog.w(TAG, " codePath=" + pkg.codePath);
10743                    Slog.w(TAG, "*************************************************");
10744                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10745                            "Core android package being redefined.  Skipping.");
10746                }
10747            }
10748
10749            // A package name must be unique; don't allow duplicates
10750            if (mPackages.containsKey(pkg.packageName)) {
10751                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10752                        "Application package " + pkg.packageName
10753                        + " already installed.  Skipping duplicate.");
10754            }
10755
10756            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10757                // Static libs have a synthetic package name containing the version
10758                // but we still want the base name to be unique.
10759                if (mPackages.containsKey(pkg.manifestPackageName)) {
10760                    throw new PackageManagerException(
10761                            "Duplicate static shared lib provider package");
10762                }
10763
10764                // Static shared libraries should have at least O target SDK
10765                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10766                    throw new PackageManagerException(
10767                            "Packages declaring static-shared libs must target O SDK or higher");
10768                }
10769
10770                // Package declaring static a shared lib cannot be instant apps
10771                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10772                    throw new PackageManagerException(
10773                            "Packages declaring static-shared libs cannot be instant apps");
10774                }
10775
10776                // Package declaring static a shared lib cannot be renamed since the package
10777                // name is synthetic and apps can't code around package manager internals.
10778                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10779                    throw new PackageManagerException(
10780                            "Packages declaring static-shared libs cannot be renamed");
10781                }
10782
10783                // Package declaring static a shared lib cannot declare child packages
10784                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10785                    throw new PackageManagerException(
10786                            "Packages declaring static-shared libs cannot have child packages");
10787                }
10788
10789                // Package declaring static a shared lib cannot declare dynamic libs
10790                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10791                    throw new PackageManagerException(
10792                            "Packages declaring static-shared libs cannot declare dynamic libs");
10793                }
10794
10795                // Package declaring static a shared lib cannot declare shared users
10796                if (pkg.mSharedUserId != null) {
10797                    throw new PackageManagerException(
10798                            "Packages declaring static-shared libs cannot declare shared users");
10799                }
10800
10801                // Static shared libs cannot declare activities
10802                if (!pkg.activities.isEmpty()) {
10803                    throw new PackageManagerException(
10804                            "Static shared libs cannot declare activities");
10805                }
10806
10807                // Static shared libs cannot declare services
10808                if (!pkg.services.isEmpty()) {
10809                    throw new PackageManagerException(
10810                            "Static shared libs cannot declare services");
10811                }
10812
10813                // Static shared libs cannot declare providers
10814                if (!pkg.providers.isEmpty()) {
10815                    throw new PackageManagerException(
10816                            "Static shared libs cannot declare content providers");
10817                }
10818
10819                // Static shared libs cannot declare receivers
10820                if (!pkg.receivers.isEmpty()) {
10821                    throw new PackageManagerException(
10822                            "Static shared libs cannot declare broadcast receivers");
10823                }
10824
10825                // Static shared libs cannot declare permission groups
10826                if (!pkg.permissionGroups.isEmpty()) {
10827                    throw new PackageManagerException(
10828                            "Static shared libs cannot declare permission groups");
10829                }
10830
10831                // Static shared libs cannot declare permissions
10832                if (!pkg.permissions.isEmpty()) {
10833                    throw new PackageManagerException(
10834                            "Static shared libs cannot declare permissions");
10835                }
10836
10837                // Static shared libs cannot declare protected broadcasts
10838                if (pkg.protectedBroadcasts != null) {
10839                    throw new PackageManagerException(
10840                            "Static shared libs cannot declare protected broadcasts");
10841                }
10842
10843                // Static shared libs cannot be overlay targets
10844                if (pkg.mOverlayTarget != null) {
10845                    throw new PackageManagerException(
10846                            "Static shared libs cannot be overlay targets");
10847                }
10848
10849                // The version codes must be ordered as lib versions
10850                long minVersionCode = Long.MIN_VALUE;
10851                long maxVersionCode = Long.MAX_VALUE;
10852
10853                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10854                        pkg.staticSharedLibName);
10855                if (versionedLib != null) {
10856                    final int versionCount = versionedLib.size();
10857                    for (int i = 0; i < versionCount; i++) {
10858                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10859                        final long libVersionCode = libInfo.getDeclaringPackage()
10860                                .getLongVersionCode();
10861                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10862                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10863                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10864                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10865                        } else {
10866                            minVersionCode = maxVersionCode = libVersionCode;
10867                            break;
10868                        }
10869                    }
10870                }
10871                if (pkg.getLongVersionCode() < minVersionCode
10872                        || pkg.getLongVersionCode() > maxVersionCode) {
10873                    throw new PackageManagerException("Static shared"
10874                            + " lib version codes must be ordered as lib versions");
10875                }
10876            }
10877
10878            // Only privileged apps and updated privileged apps can add child packages.
10879            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10880                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10881                    throw new PackageManagerException("Only privileged apps can add child "
10882                            + "packages. Ignoring package " + pkg.packageName);
10883                }
10884                final int childCount = pkg.childPackages.size();
10885                for (int i = 0; i < childCount; i++) {
10886                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10887                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10888                            childPkg.packageName)) {
10889                        throw new PackageManagerException("Can't override child of "
10890                                + "another disabled app. Ignoring package " + pkg.packageName);
10891                    }
10892                }
10893            }
10894
10895            // If we're only installing presumed-existing packages, require that the
10896            // scanned APK is both already known and at the path previously established
10897            // for it.  Previously unknown packages we pick up normally, but if we have an
10898            // a priori expectation about this package's install presence, enforce it.
10899            // With a singular exception for new system packages. When an OTA contains
10900            // a new system package, we allow the codepath to change from a system location
10901            // to the user-installed location. If we don't allow this change, any newer,
10902            // user-installed version of the application will be ignored.
10903            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10904                if (mExpectingBetter.containsKey(pkg.packageName)) {
10905                    logCriticalInfo(Log.WARN,
10906                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10907                } else {
10908                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10909                    if (known != null) {
10910                        if (DEBUG_PACKAGE_SCANNING) {
10911                            Log.d(TAG, "Examining " + pkg.codePath
10912                                    + " and requiring known paths " + known.codePathString
10913                                    + " & " + known.resourcePathString);
10914                        }
10915                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10916                                || !pkg.applicationInfo.getResourcePath().equals(
10917                                        known.resourcePathString)) {
10918                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10919                                    "Application package " + pkg.packageName
10920                                    + " found at " + pkg.applicationInfo.getCodePath()
10921                                    + " but expected at " + known.codePathString
10922                                    + "; ignoring.");
10923                        }
10924                    } else {
10925                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10926                                "Application package " + pkg.packageName
10927                                + " not found; ignoring.");
10928                    }
10929                }
10930            }
10931
10932            // Verify that this new package doesn't have any content providers
10933            // that conflict with existing packages.  Only do this if the
10934            // package isn't already installed, since we don't want to break
10935            // things that are installed.
10936            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10937                final int N = pkg.providers.size();
10938                int i;
10939                for (i=0; i<N; i++) {
10940                    PackageParser.Provider p = pkg.providers.get(i);
10941                    if (p.info.authority != null) {
10942                        String names[] = p.info.authority.split(";");
10943                        for (int j = 0; j < names.length; j++) {
10944                            if (mProvidersByAuthority.containsKey(names[j])) {
10945                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10946                                final String otherPackageName =
10947                                        ((other != null && other.getComponentName() != null) ?
10948                                                other.getComponentName().getPackageName() : "?");
10949                                throw new PackageManagerException(
10950                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10951                                        "Can't install because provider name " + names[j]
10952                                                + " (in package " + pkg.applicationInfo.packageName
10953                                                + ") is already used by " + otherPackageName);
10954                            }
10955                        }
10956                    }
10957                }
10958            }
10959
10960            // Verify that packages sharing a user with a privileged app are marked as privileged.
10961            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
10962                SharedUserSetting sharedUserSetting = null;
10963                try {
10964                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
10965                } catch (PackageManagerException ignore) {}
10966                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10967                    // Exempt SharedUsers signed with the platform key.
10968                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10969                    if ((platformPkgSetting.signatures.mSigningDetails
10970                            != PackageParser.SigningDetails.UNKNOWN)
10971                            && (compareSignatures(
10972                                    platformPkgSetting.signatures.mSigningDetails.signatures,
10973                                    pkg.mSigningDetails.signatures)
10974                                            != PackageManager.SIGNATURE_MATCH)) {
10975                        throw new PackageManagerException("Apps that share a user with a " +
10976                                "privileged app must themselves be marked as privileged. " +
10977                                pkg.packageName + " shares privileged user " +
10978                                pkg.mSharedUserId + ".");
10979                    }
10980                }
10981            }
10982
10983            // Apply policies specific for runtime resource overlays (RROs).
10984            if (pkg.mOverlayTarget != null) {
10985                // System overlays have some restrictions on their use of the 'static' state.
10986                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10987                    // We are scanning a system overlay. This can be the first scan of the
10988                    // system/vendor/oem partition, or an update to the system overlay.
10989                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10990                        // This must be an update to a system overlay.
10991                        final PackageSetting previousPkg = assertNotNull(
10992                                mSettings.getPackageLPr(pkg.packageName),
10993                                "previous package state not present");
10994
10995                        // Static overlays cannot be updated.
10996                        if (previousPkg.pkg.mOverlayIsStatic) {
10997                            throw new PackageManagerException("Overlay " + pkg.packageName +
10998                                    " is static and cannot be upgraded.");
10999                        // Non-static overlays cannot be converted to static overlays.
11000                        } else if (pkg.mOverlayIsStatic) {
11001                            throw new PackageManagerException("Overlay " + pkg.packageName +
11002                                    " cannot be upgraded into a static overlay.");
11003                        }
11004                    }
11005                } else {
11006                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11007                    if (pkg.mOverlayIsStatic) {
11008                        throw new PackageManagerException("Overlay " + pkg.packageName +
11009                                " is static but not pre-installed.");
11010                    }
11011
11012                    // The only case where we allow installation of a non-system overlay is when
11013                    // its signature is signed with the platform certificate.
11014                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11015                    if ((platformPkgSetting.signatures.mSigningDetails
11016                            != PackageParser.SigningDetails.UNKNOWN)
11017                            && (compareSignatures(
11018                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11019                                    pkg.mSigningDetails.signatures)
11020                                            != PackageManager.SIGNATURE_MATCH)) {
11021                        throw new PackageManagerException("Overlay " + pkg.packageName +
11022                                " must be signed with the platform certificate.");
11023                    }
11024                }
11025            }
11026        }
11027    }
11028
11029    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11030            int type, String declaringPackageName, long declaringVersionCode) {
11031        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11032        if (versionedLib == null) {
11033            versionedLib = new LongSparseArray<>();
11034            mSharedLibraries.put(name, versionedLib);
11035            if (type == SharedLibraryInfo.TYPE_STATIC) {
11036                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11037            }
11038        } else if (versionedLib.indexOfKey(version) >= 0) {
11039            return false;
11040        }
11041        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11042                version, type, declaringPackageName, declaringVersionCode);
11043        versionedLib.put(version, libEntry);
11044        return true;
11045    }
11046
11047    private boolean removeSharedLibraryLPw(String name, long version) {
11048        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11049        if (versionedLib == null) {
11050            return false;
11051        }
11052        final int libIdx = versionedLib.indexOfKey(version);
11053        if (libIdx < 0) {
11054            return false;
11055        }
11056        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11057        versionedLib.remove(version);
11058        if (versionedLib.size() <= 0) {
11059            mSharedLibraries.remove(name);
11060            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11061                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11062                        .getPackageName());
11063            }
11064        }
11065        return true;
11066    }
11067
11068    /**
11069     * Adds a scanned package to the system. When this method is finished, the package will
11070     * be available for query, resolution, etc...
11071     */
11072    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11073            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11074        final String pkgName = pkg.packageName;
11075        if (mCustomResolverComponentName != null &&
11076                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11077            setUpCustomResolverActivity(pkg);
11078        }
11079
11080        if (pkg.packageName.equals("android")) {
11081            synchronized (mPackages) {
11082                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11083                    // Set up information for our fall-back user intent resolution activity.
11084                    mPlatformPackage = pkg;
11085                    pkg.mVersionCode = mSdkVersion;
11086                    pkg.mVersionCodeMajor = 0;
11087                    mAndroidApplication = pkg.applicationInfo;
11088                    if (!mResolverReplaced) {
11089                        mResolveActivity.applicationInfo = mAndroidApplication;
11090                        mResolveActivity.name = ResolverActivity.class.getName();
11091                        mResolveActivity.packageName = mAndroidApplication.packageName;
11092                        mResolveActivity.processName = "system:ui";
11093                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11094                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11095                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11096                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11097                        mResolveActivity.exported = true;
11098                        mResolveActivity.enabled = true;
11099                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11100                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11101                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11102                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11103                                | ActivityInfo.CONFIG_ORIENTATION
11104                                | ActivityInfo.CONFIG_KEYBOARD
11105                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11106                        mResolveInfo.activityInfo = mResolveActivity;
11107                        mResolveInfo.priority = 0;
11108                        mResolveInfo.preferredOrder = 0;
11109                        mResolveInfo.match = 0;
11110                        mResolveComponentName = new ComponentName(
11111                                mAndroidApplication.packageName, mResolveActivity.name);
11112                    }
11113                }
11114            }
11115        }
11116
11117        ArrayList<PackageParser.Package> clientLibPkgs = null;
11118        // writer
11119        synchronized (mPackages) {
11120            boolean hasStaticSharedLibs = false;
11121
11122            // Any app can add new static shared libraries
11123            if (pkg.staticSharedLibName != null) {
11124                // Static shared libs don't allow renaming as they have synthetic package
11125                // names to allow install of multiple versions, so use name from manifest.
11126                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11127                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11128                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11129                    hasStaticSharedLibs = true;
11130                } else {
11131                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11132                                + pkg.staticSharedLibName + " already exists; skipping");
11133                }
11134                // Static shared libs cannot be updated once installed since they
11135                // use synthetic package name which includes the version code, so
11136                // not need to update other packages's shared lib dependencies.
11137            }
11138
11139            if (!hasStaticSharedLibs
11140                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11141                // Only system apps can add new dynamic shared libraries.
11142                if (pkg.libraryNames != null) {
11143                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11144                        String name = pkg.libraryNames.get(i);
11145                        boolean allowed = false;
11146                        if (pkg.isUpdatedSystemApp()) {
11147                            // New library entries can only be added through the
11148                            // system image.  This is important to get rid of a lot
11149                            // of nasty edge cases: for example if we allowed a non-
11150                            // system update of the app to add a library, then uninstalling
11151                            // the update would make the library go away, and assumptions
11152                            // we made such as through app install filtering would now
11153                            // have allowed apps on the device which aren't compatible
11154                            // with it.  Better to just have the restriction here, be
11155                            // conservative, and create many fewer cases that can negatively
11156                            // impact the user experience.
11157                            final PackageSetting sysPs = mSettings
11158                                    .getDisabledSystemPkgLPr(pkg.packageName);
11159                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11160                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11161                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11162                                        allowed = true;
11163                                        break;
11164                                    }
11165                                }
11166                            }
11167                        } else {
11168                            allowed = true;
11169                        }
11170                        if (allowed) {
11171                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11172                                    SharedLibraryInfo.VERSION_UNDEFINED,
11173                                    SharedLibraryInfo.TYPE_DYNAMIC,
11174                                    pkg.packageName, pkg.getLongVersionCode())) {
11175                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11176                                        + name + " already exists; skipping");
11177                            }
11178                        } else {
11179                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11180                                    + name + " that is not declared on system image; skipping");
11181                        }
11182                    }
11183
11184                    if ((scanFlags & SCAN_BOOTING) == 0) {
11185                        // If we are not booting, we need to update any applications
11186                        // that are clients of our shared library.  If we are booting,
11187                        // this will all be done once the scan is complete.
11188                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11189                    }
11190                }
11191            }
11192        }
11193
11194        if ((scanFlags & SCAN_BOOTING) != 0) {
11195            // No apps can run during boot scan, so they don't need to be frozen
11196        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11197            // Caller asked to not kill app, so it's probably not frozen
11198        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11199            // Caller asked us to ignore frozen check for some reason; they
11200            // probably didn't know the package name
11201        } else {
11202            // We're doing major surgery on this package, so it better be frozen
11203            // right now to keep it from launching
11204            checkPackageFrozen(pkgName);
11205        }
11206
11207        // Also need to kill any apps that are dependent on the library.
11208        if (clientLibPkgs != null) {
11209            for (int i=0; i<clientLibPkgs.size(); i++) {
11210                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11211                killApplication(clientPkg.applicationInfo.packageName,
11212                        clientPkg.applicationInfo.uid, "update lib");
11213            }
11214        }
11215
11216        // writer
11217        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11218
11219        synchronized (mPackages) {
11220            // We don't expect installation to fail beyond this point
11221
11222            // Add the new setting to mSettings
11223            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11224            // Add the new setting to mPackages
11225            mPackages.put(pkg.applicationInfo.packageName, pkg);
11226            // Make sure we don't accidentally delete its data.
11227            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11228            while (iter.hasNext()) {
11229                PackageCleanItem item = iter.next();
11230                if (pkgName.equals(item.packageName)) {
11231                    iter.remove();
11232                }
11233            }
11234
11235            // Add the package's KeySets to the global KeySetManagerService
11236            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11237            ksms.addScannedPackageLPw(pkg);
11238
11239            int N = pkg.providers.size();
11240            StringBuilder r = null;
11241            int i;
11242            for (i=0; i<N; i++) {
11243                PackageParser.Provider p = pkg.providers.get(i);
11244                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11245                        p.info.processName);
11246                mProviders.addProvider(p);
11247                p.syncable = p.info.isSyncable;
11248                if (p.info.authority != null) {
11249                    String names[] = p.info.authority.split(";");
11250                    p.info.authority = null;
11251                    for (int j = 0; j < names.length; j++) {
11252                        if (j == 1 && p.syncable) {
11253                            // We only want the first authority for a provider to possibly be
11254                            // syncable, so if we already added this provider using a different
11255                            // authority clear the syncable flag. We copy the provider before
11256                            // changing it because the mProviders object contains a reference
11257                            // to a provider that we don't want to change.
11258                            // Only do this for the second authority since the resulting provider
11259                            // object can be the same for all future authorities for this provider.
11260                            p = new PackageParser.Provider(p);
11261                            p.syncable = false;
11262                        }
11263                        if (!mProvidersByAuthority.containsKey(names[j])) {
11264                            mProvidersByAuthority.put(names[j], p);
11265                            if (p.info.authority == null) {
11266                                p.info.authority = names[j];
11267                            } else {
11268                                p.info.authority = p.info.authority + ";" + names[j];
11269                            }
11270                            if (DEBUG_PACKAGE_SCANNING) {
11271                                if (chatty)
11272                                    Log.d(TAG, "Registered content provider: " + names[j]
11273                                            + ", className = " + p.info.name + ", isSyncable = "
11274                                            + p.info.isSyncable);
11275                            }
11276                        } else {
11277                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11278                            Slog.w(TAG, "Skipping provider name " + names[j] +
11279                                    " (in package " + pkg.applicationInfo.packageName +
11280                                    "): name already used by "
11281                                    + ((other != null && other.getComponentName() != null)
11282                                            ? other.getComponentName().getPackageName() : "?"));
11283                        }
11284                    }
11285                }
11286                if (chatty) {
11287                    if (r == null) {
11288                        r = new StringBuilder(256);
11289                    } else {
11290                        r.append(' ');
11291                    }
11292                    r.append(p.info.name);
11293                }
11294            }
11295            if (r != null) {
11296                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11297            }
11298
11299            N = pkg.services.size();
11300            r = null;
11301            for (i=0; i<N; i++) {
11302                PackageParser.Service s = pkg.services.get(i);
11303                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11304                        s.info.processName);
11305                mServices.addService(s);
11306                if (chatty) {
11307                    if (r == null) {
11308                        r = new StringBuilder(256);
11309                    } else {
11310                        r.append(' ');
11311                    }
11312                    r.append(s.info.name);
11313                }
11314            }
11315            if (r != null) {
11316                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11317            }
11318
11319            N = pkg.receivers.size();
11320            r = null;
11321            for (i=0; i<N; i++) {
11322                PackageParser.Activity a = pkg.receivers.get(i);
11323                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11324                        a.info.processName);
11325                mReceivers.addActivity(a, "receiver");
11326                if (chatty) {
11327                    if (r == null) {
11328                        r = new StringBuilder(256);
11329                    } else {
11330                        r.append(' ');
11331                    }
11332                    r.append(a.info.name);
11333                }
11334            }
11335            if (r != null) {
11336                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11337            }
11338
11339            N = pkg.activities.size();
11340            r = null;
11341            for (i=0; i<N; i++) {
11342                PackageParser.Activity a = pkg.activities.get(i);
11343                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11344                        a.info.processName);
11345                mActivities.addActivity(a, "activity");
11346                if (chatty) {
11347                    if (r == null) {
11348                        r = new StringBuilder(256);
11349                    } else {
11350                        r.append(' ');
11351                    }
11352                    r.append(a.info.name);
11353                }
11354            }
11355            if (r != null) {
11356                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11357            }
11358
11359            // Don't allow ephemeral applications to define new permissions groups.
11360            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11361                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11362                        + " ignored: instant apps cannot define new permission groups.");
11363            } else {
11364                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11365            }
11366
11367            // Don't allow ephemeral applications to define new permissions.
11368            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11369                Slog.w(TAG, "Permissions from package " + pkg.packageName
11370                        + " ignored: instant apps cannot define new permissions.");
11371            } else {
11372                mPermissionManager.addAllPermissions(pkg, chatty);
11373            }
11374
11375            N = pkg.instrumentation.size();
11376            r = null;
11377            for (i=0; i<N; i++) {
11378                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11379                a.info.packageName = pkg.applicationInfo.packageName;
11380                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11381                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11382                a.info.splitNames = pkg.splitNames;
11383                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11384                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11385                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11386                a.info.dataDir = pkg.applicationInfo.dataDir;
11387                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11388                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11389                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11390                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11391                mInstrumentation.put(a.getComponentName(), a);
11392                if (chatty) {
11393                    if (r == null) {
11394                        r = new StringBuilder(256);
11395                    } else {
11396                        r.append(' ');
11397                    }
11398                    r.append(a.info.name);
11399                }
11400            }
11401            if (r != null) {
11402                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11403            }
11404
11405            if (pkg.protectedBroadcasts != null) {
11406                N = pkg.protectedBroadcasts.size();
11407                synchronized (mProtectedBroadcasts) {
11408                    for (i = 0; i < N; i++) {
11409                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11410                    }
11411                }
11412            }
11413        }
11414
11415        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11416    }
11417
11418    /**
11419     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11420     * is derived purely on the basis of the contents of {@code scanFile} and
11421     * {@code cpuAbiOverride}.
11422     *
11423     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11424     */
11425    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11426            boolean extractLibs)
11427                    throws PackageManagerException {
11428        // Give ourselves some initial paths; we'll come back for another
11429        // pass once we've determined ABI below.
11430        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11431
11432        // We would never need to extract libs for forward-locked and external packages,
11433        // since the container service will do it for us. We shouldn't attempt to
11434        // extract libs from system app when it was not updated.
11435        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11436                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11437            extractLibs = false;
11438        }
11439
11440        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11441        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11442
11443        NativeLibraryHelper.Handle handle = null;
11444        try {
11445            handle = NativeLibraryHelper.Handle.create(pkg);
11446            // TODO(multiArch): This can be null for apps that didn't go through the
11447            // usual installation process. We can calculate it again, like we
11448            // do during install time.
11449            //
11450            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11451            // unnecessary.
11452            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11453
11454            // Null out the abis so that they can be recalculated.
11455            pkg.applicationInfo.primaryCpuAbi = null;
11456            pkg.applicationInfo.secondaryCpuAbi = null;
11457            if (isMultiArch(pkg.applicationInfo)) {
11458                // Warn if we've set an abiOverride for multi-lib packages..
11459                // By definition, we need to copy both 32 and 64 bit libraries for
11460                // such packages.
11461                if (pkg.cpuAbiOverride != null
11462                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11463                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11464                }
11465
11466                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11467                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11468                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11469                    if (extractLibs) {
11470                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11471                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11472                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11473                                useIsaSpecificSubdirs);
11474                    } else {
11475                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11476                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11477                    }
11478                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11479                }
11480
11481                // Shared library native code should be in the APK zip aligned
11482                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11483                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11484                            "Shared library native lib extraction not supported");
11485                }
11486
11487                maybeThrowExceptionForMultiArchCopy(
11488                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11489
11490                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11491                    if (extractLibs) {
11492                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11493                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11494                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11495                                useIsaSpecificSubdirs);
11496                    } else {
11497                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11498                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11499                    }
11500                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11501                }
11502
11503                maybeThrowExceptionForMultiArchCopy(
11504                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11505
11506                if (abi64 >= 0) {
11507                    // Shared library native libs should be in the APK zip aligned
11508                    if (extractLibs && pkg.isLibrary()) {
11509                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11510                                "Shared library native lib extraction not supported");
11511                    }
11512                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11513                }
11514
11515                if (abi32 >= 0) {
11516                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11517                    if (abi64 >= 0) {
11518                        if (pkg.use32bitAbi) {
11519                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11520                            pkg.applicationInfo.primaryCpuAbi = abi;
11521                        } else {
11522                            pkg.applicationInfo.secondaryCpuAbi = abi;
11523                        }
11524                    } else {
11525                        pkg.applicationInfo.primaryCpuAbi = abi;
11526                    }
11527                }
11528            } else {
11529                String[] abiList = (cpuAbiOverride != null) ?
11530                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11531
11532                // Enable gross and lame hacks for apps that are built with old
11533                // SDK tools. We must scan their APKs for renderscript bitcode and
11534                // not launch them if it's present. Don't bother checking on devices
11535                // that don't have 64 bit support.
11536                boolean needsRenderScriptOverride = false;
11537                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11538                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11539                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11540                    needsRenderScriptOverride = true;
11541                }
11542
11543                final int copyRet;
11544                if (extractLibs) {
11545                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11546                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11547                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11548                } else {
11549                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11550                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11551                }
11552                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11553
11554                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11555                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11556                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11557                }
11558
11559                if (copyRet >= 0) {
11560                    // Shared libraries that have native libs must be multi-architecture
11561                    if (pkg.isLibrary()) {
11562                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11563                                "Shared library with native libs must be multiarch");
11564                    }
11565                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11566                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11567                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11568                } else if (needsRenderScriptOverride) {
11569                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11570                }
11571            }
11572        } catch (IOException ioe) {
11573            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11574        } finally {
11575            IoUtils.closeQuietly(handle);
11576        }
11577
11578        // Now that we've calculated the ABIs and determined if it's an internal app,
11579        // we will go ahead and populate the nativeLibraryPath.
11580        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11581    }
11582
11583    /**
11584     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11585     * i.e, so that all packages can be run inside a single process if required.
11586     *
11587     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11588     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11589     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11590     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11591     * updating a package that belongs to a shared user.
11592     *
11593     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11594     * adds unnecessary complexity.
11595     */
11596    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11597            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11598        List<String> changedAbiCodePath = null;
11599        String requiredInstructionSet = null;
11600        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11601            requiredInstructionSet = VMRuntime.getInstructionSet(
11602                     scannedPackage.applicationInfo.primaryCpuAbi);
11603        }
11604
11605        PackageSetting requirer = null;
11606        for (PackageSetting ps : packagesForUser) {
11607            // If packagesForUser contains scannedPackage, we skip it. This will happen
11608            // when scannedPackage is an update of an existing package. Without this check,
11609            // we will never be able to change the ABI of any package belonging to a shared
11610            // user, even if it's compatible with other packages.
11611            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11612                if (ps.primaryCpuAbiString == null) {
11613                    continue;
11614                }
11615
11616                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11617                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11618                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11619                    // this but there's not much we can do.
11620                    String errorMessage = "Instruction set mismatch, "
11621                            + ((requirer == null) ? "[caller]" : requirer)
11622                            + " requires " + requiredInstructionSet + " whereas " + ps
11623                            + " requires " + instructionSet;
11624                    Slog.w(TAG, errorMessage);
11625                }
11626
11627                if (requiredInstructionSet == null) {
11628                    requiredInstructionSet = instructionSet;
11629                    requirer = ps;
11630                }
11631            }
11632        }
11633
11634        if (requiredInstructionSet != null) {
11635            String adjustedAbi;
11636            if (requirer != null) {
11637                // requirer != null implies that either scannedPackage was null or that scannedPackage
11638                // did not require an ABI, in which case we have to adjust scannedPackage to match
11639                // the ABI of the set (which is the same as requirer's ABI)
11640                adjustedAbi = requirer.primaryCpuAbiString;
11641                if (scannedPackage != null) {
11642                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11643                }
11644            } else {
11645                // requirer == null implies that we're updating all ABIs in the set to
11646                // match scannedPackage.
11647                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11648            }
11649
11650            for (PackageSetting ps : packagesForUser) {
11651                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11652                    if (ps.primaryCpuAbiString != null) {
11653                        continue;
11654                    }
11655
11656                    ps.primaryCpuAbiString = adjustedAbi;
11657                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11658                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11659                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11660                        if (DEBUG_ABI_SELECTION) {
11661                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11662                                    + " (requirer="
11663                                    + (requirer != null ? requirer.pkg : "null")
11664                                    + ", scannedPackage="
11665                                    + (scannedPackage != null ? scannedPackage : "null")
11666                                    + ")");
11667                        }
11668                        if (changedAbiCodePath == null) {
11669                            changedAbiCodePath = new ArrayList<>();
11670                        }
11671                        changedAbiCodePath.add(ps.codePathString);
11672                    }
11673                }
11674            }
11675        }
11676        return changedAbiCodePath;
11677    }
11678
11679    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11680        synchronized (mPackages) {
11681            mResolverReplaced = true;
11682            // Set up information for custom user intent resolution activity.
11683            mResolveActivity.applicationInfo = pkg.applicationInfo;
11684            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11685            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11686            mResolveActivity.processName = pkg.applicationInfo.packageName;
11687            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11688            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11689                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11690            mResolveActivity.theme = 0;
11691            mResolveActivity.exported = true;
11692            mResolveActivity.enabled = true;
11693            mResolveInfo.activityInfo = mResolveActivity;
11694            mResolveInfo.priority = 0;
11695            mResolveInfo.preferredOrder = 0;
11696            mResolveInfo.match = 0;
11697            mResolveComponentName = mCustomResolverComponentName;
11698            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11699                    mResolveComponentName);
11700        }
11701    }
11702
11703    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11704        if (installerActivity == null) {
11705            if (DEBUG_INSTANT) {
11706                Slog.d(TAG, "Clear ephemeral installer activity");
11707            }
11708            mInstantAppInstallerActivity = null;
11709            return;
11710        }
11711
11712        if (DEBUG_INSTANT) {
11713            Slog.d(TAG, "Set ephemeral installer activity: "
11714                    + installerActivity.getComponentName());
11715        }
11716        // Set up information for ephemeral installer activity
11717        mInstantAppInstallerActivity = installerActivity;
11718        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11719                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11720        mInstantAppInstallerActivity.exported = true;
11721        mInstantAppInstallerActivity.enabled = true;
11722        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11723        mInstantAppInstallerInfo.priority = 1;
11724        mInstantAppInstallerInfo.preferredOrder = 1;
11725        mInstantAppInstallerInfo.isDefault = true;
11726        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11727                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11728    }
11729
11730    private static String calculateBundledApkRoot(final String codePathString) {
11731        final File codePath = new File(codePathString);
11732        final File codeRoot;
11733        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11734            codeRoot = Environment.getRootDirectory();
11735        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11736            codeRoot = Environment.getOemDirectory();
11737        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11738            codeRoot = Environment.getVendorDirectory();
11739        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11740            codeRoot = Environment.getProductDirectory();
11741        } else {
11742            // Unrecognized code path; take its top real segment as the apk root:
11743            // e.g. /something/app/blah.apk => /something
11744            try {
11745                File f = codePath.getCanonicalFile();
11746                File parent = f.getParentFile();    // non-null because codePath is a file
11747                File tmp;
11748                while ((tmp = parent.getParentFile()) != null) {
11749                    f = parent;
11750                    parent = tmp;
11751                }
11752                codeRoot = f;
11753                Slog.w(TAG, "Unrecognized code path "
11754                        + codePath + " - using " + codeRoot);
11755            } catch (IOException e) {
11756                // Can't canonicalize the code path -- shenanigans?
11757                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11758                return Environment.getRootDirectory().getPath();
11759            }
11760        }
11761        return codeRoot.getPath();
11762    }
11763
11764    /**
11765     * Derive and set the location of native libraries for the given package,
11766     * which varies depending on where and how the package was installed.
11767     */
11768    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11769        final ApplicationInfo info = pkg.applicationInfo;
11770        final String codePath = pkg.codePath;
11771        final File codeFile = new File(codePath);
11772        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11773        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11774
11775        info.nativeLibraryRootDir = null;
11776        info.nativeLibraryRootRequiresIsa = false;
11777        info.nativeLibraryDir = null;
11778        info.secondaryNativeLibraryDir = null;
11779
11780        if (isApkFile(codeFile)) {
11781            // Monolithic install
11782            if (bundledApp) {
11783                // If "/system/lib64/apkname" exists, assume that is the per-package
11784                // native library directory to use; otherwise use "/system/lib/apkname".
11785                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11786                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11787                        getPrimaryInstructionSet(info));
11788
11789                // This is a bundled system app so choose the path based on the ABI.
11790                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11791                // is just the default path.
11792                final String apkName = deriveCodePathName(codePath);
11793                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11794                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11795                        apkName).getAbsolutePath();
11796
11797                if (info.secondaryCpuAbi != null) {
11798                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11799                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11800                            secondaryLibDir, apkName).getAbsolutePath();
11801                }
11802            } else if (asecApp) {
11803                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11804                        .getAbsolutePath();
11805            } else {
11806                final String apkName = deriveCodePathName(codePath);
11807                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11808                        .getAbsolutePath();
11809            }
11810
11811            info.nativeLibraryRootRequiresIsa = false;
11812            info.nativeLibraryDir = info.nativeLibraryRootDir;
11813        } else {
11814            // Cluster install
11815            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11816            info.nativeLibraryRootRequiresIsa = true;
11817
11818            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11819                    getPrimaryInstructionSet(info)).getAbsolutePath();
11820
11821            if (info.secondaryCpuAbi != null) {
11822                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11823                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11824            }
11825        }
11826    }
11827
11828    /**
11829     * Calculate the abis and roots for a bundled app. These can uniquely
11830     * be determined from the contents of the system partition, i.e whether
11831     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11832     * of this information, and instead assume that the system was built
11833     * sensibly.
11834     */
11835    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11836                                           PackageSetting pkgSetting) {
11837        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11838
11839        // If "/system/lib64/apkname" exists, assume that is the per-package
11840        // native library directory to use; otherwise use "/system/lib/apkname".
11841        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11842        setBundledAppAbi(pkg, apkRoot, apkName);
11843        // pkgSetting might be null during rescan following uninstall of updates
11844        // to a bundled app, so accommodate that possibility.  The settings in
11845        // that case will be established later from the parsed package.
11846        //
11847        // If the settings aren't null, sync them up with what we've just derived.
11848        // note that apkRoot isn't stored in the package settings.
11849        if (pkgSetting != null) {
11850            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11851            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11852        }
11853    }
11854
11855    /**
11856     * Deduces the ABI of a bundled app and sets the relevant fields on the
11857     * parsed pkg object.
11858     *
11859     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11860     *        under which system libraries are installed.
11861     * @param apkName the name of the installed package.
11862     */
11863    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11864        final File codeFile = new File(pkg.codePath);
11865
11866        final boolean has64BitLibs;
11867        final boolean has32BitLibs;
11868        if (isApkFile(codeFile)) {
11869            // Monolithic install
11870            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11871            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11872        } else {
11873            // Cluster install
11874            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11875            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11876                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11877                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11878                has64BitLibs = (new File(rootDir, isa)).exists();
11879            } else {
11880                has64BitLibs = false;
11881            }
11882            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11883                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11884                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11885                has32BitLibs = (new File(rootDir, isa)).exists();
11886            } else {
11887                has32BitLibs = false;
11888            }
11889        }
11890
11891        if (has64BitLibs && !has32BitLibs) {
11892            // The package has 64 bit libs, but not 32 bit libs. Its primary
11893            // ABI should be 64 bit. We can safely assume here that the bundled
11894            // native libraries correspond to the most preferred ABI in the list.
11895
11896            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11897            pkg.applicationInfo.secondaryCpuAbi = null;
11898        } else if (has32BitLibs && !has64BitLibs) {
11899            // The package has 32 bit libs but not 64 bit libs. Its primary
11900            // ABI should be 32 bit.
11901
11902            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11903            pkg.applicationInfo.secondaryCpuAbi = null;
11904        } else if (has32BitLibs && has64BitLibs) {
11905            // The application has both 64 and 32 bit bundled libraries. We check
11906            // here that the app declares multiArch support, and warn if it doesn't.
11907            //
11908            // We will be lenient here and record both ABIs. The primary will be the
11909            // ABI that's higher on the list, i.e, a device that's configured to prefer
11910            // 64 bit apps will see a 64 bit primary ABI,
11911
11912            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11913                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11914            }
11915
11916            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11917                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11918                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11919            } else {
11920                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11921                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11922            }
11923        } else {
11924            pkg.applicationInfo.primaryCpuAbi = null;
11925            pkg.applicationInfo.secondaryCpuAbi = null;
11926        }
11927    }
11928
11929    private void killApplication(String pkgName, int appId, String reason) {
11930        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11931    }
11932
11933    private void killApplication(String pkgName, int appId, int userId, String reason) {
11934        // Request the ActivityManager to kill the process(only for existing packages)
11935        // so that we do not end up in a confused state while the user is still using the older
11936        // version of the application while the new one gets installed.
11937        final long token = Binder.clearCallingIdentity();
11938        try {
11939            IActivityManager am = ActivityManager.getService();
11940            if (am != null) {
11941                try {
11942                    am.killApplication(pkgName, appId, userId, reason);
11943                } catch (RemoteException e) {
11944                }
11945            }
11946        } finally {
11947            Binder.restoreCallingIdentity(token);
11948        }
11949    }
11950
11951    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11952        // Remove the parent package setting
11953        PackageSetting ps = (PackageSetting) pkg.mExtras;
11954        if (ps != null) {
11955            removePackageLI(ps, chatty);
11956        }
11957        // Remove the child package setting
11958        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11959        for (int i = 0; i < childCount; i++) {
11960            PackageParser.Package childPkg = pkg.childPackages.get(i);
11961            ps = (PackageSetting) childPkg.mExtras;
11962            if (ps != null) {
11963                removePackageLI(ps, chatty);
11964            }
11965        }
11966    }
11967
11968    void removePackageLI(PackageSetting ps, boolean chatty) {
11969        if (DEBUG_INSTALL) {
11970            if (chatty)
11971                Log.d(TAG, "Removing package " + ps.name);
11972        }
11973
11974        // writer
11975        synchronized (mPackages) {
11976            mPackages.remove(ps.name);
11977            final PackageParser.Package pkg = ps.pkg;
11978            if (pkg != null) {
11979                cleanPackageDataStructuresLILPw(pkg, chatty);
11980            }
11981        }
11982    }
11983
11984    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11985        if (DEBUG_INSTALL) {
11986            if (chatty)
11987                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11988        }
11989
11990        // writer
11991        synchronized (mPackages) {
11992            // Remove the parent package
11993            mPackages.remove(pkg.applicationInfo.packageName);
11994            cleanPackageDataStructuresLILPw(pkg, chatty);
11995
11996            // Remove the child packages
11997            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11998            for (int i = 0; i < childCount; i++) {
11999                PackageParser.Package childPkg = pkg.childPackages.get(i);
12000                mPackages.remove(childPkg.applicationInfo.packageName);
12001                cleanPackageDataStructuresLILPw(childPkg, chatty);
12002            }
12003        }
12004    }
12005
12006    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12007        int N = pkg.providers.size();
12008        StringBuilder r = null;
12009        int i;
12010        for (i=0; i<N; i++) {
12011            PackageParser.Provider p = pkg.providers.get(i);
12012            mProviders.removeProvider(p);
12013            if (p.info.authority == null) {
12014
12015                /* There was another ContentProvider with this authority when
12016                 * this app was installed so this authority is null,
12017                 * Ignore it as we don't have to unregister the provider.
12018                 */
12019                continue;
12020            }
12021            String names[] = p.info.authority.split(";");
12022            for (int j = 0; j < names.length; j++) {
12023                if (mProvidersByAuthority.get(names[j]) == p) {
12024                    mProvidersByAuthority.remove(names[j]);
12025                    if (DEBUG_REMOVE) {
12026                        if (chatty)
12027                            Log.d(TAG, "Unregistered content provider: " + names[j]
12028                                    + ", className = " + p.info.name + ", isSyncable = "
12029                                    + p.info.isSyncable);
12030                    }
12031                }
12032            }
12033            if (DEBUG_REMOVE && chatty) {
12034                if (r == null) {
12035                    r = new StringBuilder(256);
12036                } else {
12037                    r.append(' ');
12038                }
12039                r.append(p.info.name);
12040            }
12041        }
12042        if (r != null) {
12043            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12044        }
12045
12046        N = pkg.services.size();
12047        r = null;
12048        for (i=0; i<N; i++) {
12049            PackageParser.Service s = pkg.services.get(i);
12050            mServices.removeService(s);
12051            if (chatty) {
12052                if (r == null) {
12053                    r = new StringBuilder(256);
12054                } else {
12055                    r.append(' ');
12056                }
12057                r.append(s.info.name);
12058            }
12059        }
12060        if (r != null) {
12061            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12062        }
12063
12064        N = pkg.receivers.size();
12065        r = null;
12066        for (i=0; i<N; i++) {
12067            PackageParser.Activity a = pkg.receivers.get(i);
12068            mReceivers.removeActivity(a, "receiver");
12069            if (DEBUG_REMOVE && chatty) {
12070                if (r == null) {
12071                    r = new StringBuilder(256);
12072                } else {
12073                    r.append(' ');
12074                }
12075                r.append(a.info.name);
12076            }
12077        }
12078        if (r != null) {
12079            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12080        }
12081
12082        N = pkg.activities.size();
12083        r = null;
12084        for (i=0; i<N; i++) {
12085            PackageParser.Activity a = pkg.activities.get(i);
12086            mActivities.removeActivity(a, "activity");
12087            if (DEBUG_REMOVE && chatty) {
12088                if (r == null) {
12089                    r = new StringBuilder(256);
12090                } else {
12091                    r.append(' ');
12092                }
12093                r.append(a.info.name);
12094            }
12095        }
12096        if (r != null) {
12097            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12098        }
12099
12100        mPermissionManager.removeAllPermissions(pkg, chatty);
12101
12102        N = pkg.instrumentation.size();
12103        r = null;
12104        for (i=0; i<N; i++) {
12105            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12106            mInstrumentation.remove(a.getComponentName());
12107            if (DEBUG_REMOVE && chatty) {
12108                if (r == null) {
12109                    r = new StringBuilder(256);
12110                } else {
12111                    r.append(' ');
12112                }
12113                r.append(a.info.name);
12114            }
12115        }
12116        if (r != null) {
12117            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12118        }
12119
12120        r = null;
12121        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12122            // Only system apps can hold shared libraries.
12123            if (pkg.libraryNames != null) {
12124                for (i = 0; i < pkg.libraryNames.size(); i++) {
12125                    String name = pkg.libraryNames.get(i);
12126                    if (removeSharedLibraryLPw(name, 0)) {
12127                        if (DEBUG_REMOVE && chatty) {
12128                            if (r == null) {
12129                                r = new StringBuilder(256);
12130                            } else {
12131                                r.append(' ');
12132                            }
12133                            r.append(name);
12134                        }
12135                    }
12136                }
12137            }
12138        }
12139
12140        r = null;
12141
12142        // Any package can hold static shared libraries.
12143        if (pkg.staticSharedLibName != null) {
12144            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12145                if (DEBUG_REMOVE && chatty) {
12146                    if (r == null) {
12147                        r = new StringBuilder(256);
12148                    } else {
12149                        r.append(' ');
12150                    }
12151                    r.append(pkg.staticSharedLibName);
12152                }
12153            }
12154        }
12155
12156        if (r != null) {
12157            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12158        }
12159    }
12160
12161
12162    final class ActivityIntentResolver
12163            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12164        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12165                boolean defaultOnly, int userId) {
12166            if (!sUserManager.exists(userId)) return null;
12167            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12168            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12169        }
12170
12171        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12172                int userId) {
12173            if (!sUserManager.exists(userId)) return null;
12174            mFlags = flags;
12175            return super.queryIntent(intent, resolvedType,
12176                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12177                    userId);
12178        }
12179
12180        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12181                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12182            if (!sUserManager.exists(userId)) return null;
12183            if (packageActivities == null) {
12184                return null;
12185            }
12186            mFlags = flags;
12187            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12188            final int N = packageActivities.size();
12189            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12190                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12191
12192            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12193            for (int i = 0; i < N; ++i) {
12194                intentFilters = packageActivities.get(i).intents;
12195                if (intentFilters != null && intentFilters.size() > 0) {
12196                    PackageParser.ActivityIntentInfo[] array =
12197                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12198                    intentFilters.toArray(array);
12199                    listCut.add(array);
12200                }
12201            }
12202            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12203        }
12204
12205        /**
12206         * Finds a privileged activity that matches the specified activity names.
12207         */
12208        private PackageParser.Activity findMatchingActivity(
12209                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12210            for (PackageParser.Activity sysActivity : activityList) {
12211                if (sysActivity.info.name.equals(activityInfo.name)) {
12212                    return sysActivity;
12213                }
12214                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12215                    return sysActivity;
12216                }
12217                if (sysActivity.info.targetActivity != null) {
12218                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12219                        return sysActivity;
12220                    }
12221                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12222                        return sysActivity;
12223                    }
12224                }
12225            }
12226            return null;
12227        }
12228
12229        public class IterGenerator<E> {
12230            public Iterator<E> generate(ActivityIntentInfo info) {
12231                return null;
12232            }
12233        }
12234
12235        public class ActionIterGenerator extends IterGenerator<String> {
12236            @Override
12237            public Iterator<String> generate(ActivityIntentInfo info) {
12238                return info.actionsIterator();
12239            }
12240        }
12241
12242        public class CategoriesIterGenerator extends IterGenerator<String> {
12243            @Override
12244            public Iterator<String> generate(ActivityIntentInfo info) {
12245                return info.categoriesIterator();
12246            }
12247        }
12248
12249        public class SchemesIterGenerator extends IterGenerator<String> {
12250            @Override
12251            public Iterator<String> generate(ActivityIntentInfo info) {
12252                return info.schemesIterator();
12253            }
12254        }
12255
12256        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12257            @Override
12258            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12259                return info.authoritiesIterator();
12260            }
12261        }
12262
12263        /**
12264         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12265         * MODIFIED. Do not pass in a list that should not be changed.
12266         */
12267        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12268                IterGenerator<T> generator, Iterator<T> searchIterator) {
12269            // loop through the set of actions; every one must be found in the intent filter
12270            while (searchIterator.hasNext()) {
12271                // we must have at least one filter in the list to consider a match
12272                if (intentList.size() == 0) {
12273                    break;
12274                }
12275
12276                final T searchAction = searchIterator.next();
12277
12278                // loop through the set of intent filters
12279                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12280                while (intentIter.hasNext()) {
12281                    final ActivityIntentInfo intentInfo = intentIter.next();
12282                    boolean selectionFound = false;
12283
12284                    // loop through the intent filter's selection criteria; at least one
12285                    // of them must match the searched criteria
12286                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12287                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12288                        final T intentSelection = intentSelectionIter.next();
12289                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12290                            selectionFound = true;
12291                            break;
12292                        }
12293                    }
12294
12295                    // the selection criteria wasn't found in this filter's set; this filter
12296                    // is not a potential match
12297                    if (!selectionFound) {
12298                        intentIter.remove();
12299                    }
12300                }
12301            }
12302        }
12303
12304        private boolean isProtectedAction(ActivityIntentInfo filter) {
12305            final Iterator<String> actionsIter = filter.actionsIterator();
12306            while (actionsIter != null && actionsIter.hasNext()) {
12307                final String filterAction = actionsIter.next();
12308                if (PROTECTED_ACTIONS.contains(filterAction)) {
12309                    return true;
12310                }
12311            }
12312            return false;
12313        }
12314
12315        /**
12316         * Adjusts the priority of the given intent filter according to policy.
12317         * <p>
12318         * <ul>
12319         * <li>The priority for non privileged applications is capped to '0'</li>
12320         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12321         * <li>The priority for unbundled updates to privileged applications is capped to the
12322         *      priority defined on the system partition</li>
12323         * </ul>
12324         * <p>
12325         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12326         * allowed to obtain any priority on any action.
12327         */
12328        private void adjustPriority(
12329                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12330            // nothing to do; priority is fine as-is
12331            if (intent.getPriority() <= 0) {
12332                return;
12333            }
12334
12335            final ActivityInfo activityInfo = intent.activity.info;
12336            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12337
12338            final boolean privilegedApp =
12339                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12340            if (!privilegedApp) {
12341                // non-privileged applications can never define a priority >0
12342                if (DEBUG_FILTERS) {
12343                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12344                            + " package: " + applicationInfo.packageName
12345                            + " activity: " + intent.activity.className
12346                            + " origPrio: " + intent.getPriority());
12347                }
12348                intent.setPriority(0);
12349                return;
12350            }
12351
12352            if (systemActivities == null) {
12353                // the system package is not disabled; we're parsing the system partition
12354                if (isProtectedAction(intent)) {
12355                    if (mDeferProtectedFilters) {
12356                        // We can't deal with these just yet. No component should ever obtain a
12357                        // >0 priority for a protected actions, with ONE exception -- the setup
12358                        // wizard. The setup wizard, however, cannot be known until we're able to
12359                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12360                        // until all intent filters have been processed. Chicken, meet egg.
12361                        // Let the filter temporarily have a high priority and rectify the
12362                        // priorities after all system packages have been scanned.
12363                        mProtectedFilters.add(intent);
12364                        if (DEBUG_FILTERS) {
12365                            Slog.i(TAG, "Protected action; save for later;"
12366                                    + " package: " + applicationInfo.packageName
12367                                    + " activity: " + intent.activity.className
12368                                    + " origPrio: " + intent.getPriority());
12369                        }
12370                        return;
12371                    } else {
12372                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12373                            Slog.i(TAG, "No setup wizard;"
12374                                + " All protected intents capped to priority 0");
12375                        }
12376                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12377                            if (DEBUG_FILTERS) {
12378                                Slog.i(TAG, "Found setup wizard;"
12379                                    + " allow priority " + intent.getPriority() + ";"
12380                                    + " package: " + intent.activity.info.packageName
12381                                    + " activity: " + intent.activity.className
12382                                    + " priority: " + intent.getPriority());
12383                            }
12384                            // setup wizard gets whatever it wants
12385                            return;
12386                        }
12387                        if (DEBUG_FILTERS) {
12388                            Slog.i(TAG, "Protected action; cap priority to 0;"
12389                                    + " package: " + intent.activity.info.packageName
12390                                    + " activity: " + intent.activity.className
12391                                    + " origPrio: " + intent.getPriority());
12392                        }
12393                        intent.setPriority(0);
12394                        return;
12395                    }
12396                }
12397                // privileged apps on the system image get whatever priority they request
12398                return;
12399            }
12400
12401            // privileged app unbundled update ... try to find the same activity
12402            final PackageParser.Activity foundActivity =
12403                    findMatchingActivity(systemActivities, activityInfo);
12404            if (foundActivity == null) {
12405                // this is a new activity; it cannot obtain >0 priority
12406                if (DEBUG_FILTERS) {
12407                    Slog.i(TAG, "New activity; cap priority to 0;"
12408                            + " package: " + applicationInfo.packageName
12409                            + " activity: " + intent.activity.className
12410                            + " origPrio: " + intent.getPriority());
12411                }
12412                intent.setPriority(0);
12413                return;
12414            }
12415
12416            // found activity, now check for filter equivalence
12417
12418            // a shallow copy is enough; we modify the list, not its contents
12419            final List<ActivityIntentInfo> intentListCopy =
12420                    new ArrayList<>(foundActivity.intents);
12421            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12422
12423            // find matching action subsets
12424            final Iterator<String> actionsIterator = intent.actionsIterator();
12425            if (actionsIterator != null) {
12426                getIntentListSubset(
12427                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12428                if (intentListCopy.size() == 0) {
12429                    // no more intents to match; we're not equivalent
12430                    if (DEBUG_FILTERS) {
12431                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12432                                + " package: " + applicationInfo.packageName
12433                                + " activity: " + intent.activity.className
12434                                + " origPrio: " + intent.getPriority());
12435                    }
12436                    intent.setPriority(0);
12437                    return;
12438                }
12439            }
12440
12441            // find matching category subsets
12442            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12443            if (categoriesIterator != null) {
12444                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12445                        categoriesIterator);
12446                if (intentListCopy.size() == 0) {
12447                    // no more intents to match; we're not equivalent
12448                    if (DEBUG_FILTERS) {
12449                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12450                                + " package: " + applicationInfo.packageName
12451                                + " activity: " + intent.activity.className
12452                                + " origPrio: " + intent.getPriority());
12453                    }
12454                    intent.setPriority(0);
12455                    return;
12456                }
12457            }
12458
12459            // find matching schemes subsets
12460            final Iterator<String> schemesIterator = intent.schemesIterator();
12461            if (schemesIterator != null) {
12462                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12463                        schemesIterator);
12464                if (intentListCopy.size() == 0) {
12465                    // no more intents to match; we're not equivalent
12466                    if (DEBUG_FILTERS) {
12467                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12468                                + " package: " + applicationInfo.packageName
12469                                + " activity: " + intent.activity.className
12470                                + " origPrio: " + intent.getPriority());
12471                    }
12472                    intent.setPriority(0);
12473                    return;
12474                }
12475            }
12476
12477            // find matching authorities subsets
12478            final Iterator<IntentFilter.AuthorityEntry>
12479                    authoritiesIterator = intent.authoritiesIterator();
12480            if (authoritiesIterator != null) {
12481                getIntentListSubset(intentListCopy,
12482                        new AuthoritiesIterGenerator(),
12483                        authoritiesIterator);
12484                if (intentListCopy.size() == 0) {
12485                    // no more intents to match; we're not equivalent
12486                    if (DEBUG_FILTERS) {
12487                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12488                                + " package: " + applicationInfo.packageName
12489                                + " activity: " + intent.activity.className
12490                                + " origPrio: " + intent.getPriority());
12491                    }
12492                    intent.setPriority(0);
12493                    return;
12494                }
12495            }
12496
12497            // we found matching filter(s); app gets the max priority of all intents
12498            int cappedPriority = 0;
12499            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12500                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12501            }
12502            if (intent.getPriority() > cappedPriority) {
12503                if (DEBUG_FILTERS) {
12504                    Slog.i(TAG, "Found matching filter(s);"
12505                            + " cap priority to " + cappedPriority + ";"
12506                            + " package: " + applicationInfo.packageName
12507                            + " activity: " + intent.activity.className
12508                            + " origPrio: " + intent.getPriority());
12509                }
12510                intent.setPriority(cappedPriority);
12511                return;
12512            }
12513            // all this for nothing; the requested priority was <= what was on the system
12514        }
12515
12516        public final void addActivity(PackageParser.Activity a, String type) {
12517            mActivities.put(a.getComponentName(), a);
12518            if (DEBUG_SHOW_INFO)
12519                Log.v(
12520                TAG, "  " + type + " " +
12521                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12522            if (DEBUG_SHOW_INFO)
12523                Log.v(TAG, "    Class=" + a.info.name);
12524            final int NI = a.intents.size();
12525            for (int j=0; j<NI; j++) {
12526                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12527                if ("activity".equals(type)) {
12528                    final PackageSetting ps =
12529                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12530                    final List<PackageParser.Activity> systemActivities =
12531                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12532                    adjustPriority(systemActivities, intent);
12533                }
12534                if (DEBUG_SHOW_INFO) {
12535                    Log.v(TAG, "    IntentFilter:");
12536                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12537                }
12538                if (!intent.debugCheck()) {
12539                    Log.w(TAG, "==> For Activity " + a.info.name);
12540                }
12541                addFilter(intent);
12542            }
12543        }
12544
12545        public final void removeActivity(PackageParser.Activity a, String type) {
12546            mActivities.remove(a.getComponentName());
12547            if (DEBUG_SHOW_INFO) {
12548                Log.v(TAG, "  " + type + " "
12549                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12550                                : a.info.name) + ":");
12551                Log.v(TAG, "    Class=" + a.info.name);
12552            }
12553            final int NI = a.intents.size();
12554            for (int j=0; j<NI; j++) {
12555                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12556                if (DEBUG_SHOW_INFO) {
12557                    Log.v(TAG, "    IntentFilter:");
12558                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12559                }
12560                removeFilter(intent);
12561            }
12562        }
12563
12564        @Override
12565        protected boolean allowFilterResult(
12566                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12567            ActivityInfo filterAi = filter.activity.info;
12568            for (int i=dest.size()-1; i>=0; i--) {
12569                ActivityInfo destAi = dest.get(i).activityInfo;
12570                if (destAi.name == filterAi.name
12571                        && destAi.packageName == filterAi.packageName) {
12572                    return false;
12573                }
12574            }
12575            return true;
12576        }
12577
12578        @Override
12579        protected ActivityIntentInfo[] newArray(int size) {
12580            return new ActivityIntentInfo[size];
12581        }
12582
12583        @Override
12584        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12585            if (!sUserManager.exists(userId)) return true;
12586            PackageParser.Package p = filter.activity.owner;
12587            if (p != null) {
12588                PackageSetting ps = (PackageSetting)p.mExtras;
12589                if (ps != null) {
12590                    // System apps are never considered stopped for purposes of
12591                    // filtering, because there may be no way for the user to
12592                    // actually re-launch them.
12593                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12594                            && ps.getStopped(userId);
12595                }
12596            }
12597            return false;
12598        }
12599
12600        @Override
12601        protected boolean isPackageForFilter(String packageName,
12602                PackageParser.ActivityIntentInfo info) {
12603            return packageName.equals(info.activity.owner.packageName);
12604        }
12605
12606        @Override
12607        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12608                int match, int userId) {
12609            if (!sUserManager.exists(userId)) return null;
12610            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12611                return null;
12612            }
12613            final PackageParser.Activity activity = info.activity;
12614            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12615            if (ps == null) {
12616                return null;
12617            }
12618            final PackageUserState userState = ps.readUserState(userId);
12619            ActivityInfo ai =
12620                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12621            if (ai == null) {
12622                return null;
12623            }
12624            final boolean matchExplicitlyVisibleOnly =
12625                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12626            final boolean matchVisibleToInstantApp =
12627                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12628            final boolean componentVisible =
12629                    matchVisibleToInstantApp
12630                    && info.isVisibleToInstantApp()
12631                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12632            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12633            // throw out filters that aren't visible to ephemeral apps
12634            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12635                return null;
12636            }
12637            // throw out instant app filters if we're not explicitly requesting them
12638            if (!matchInstantApp && userState.instantApp) {
12639                return null;
12640            }
12641            // throw out instant app filters if updates are available; will trigger
12642            // instant app resolution
12643            if (userState.instantApp && ps.isUpdateAvailable()) {
12644                return null;
12645            }
12646            final ResolveInfo res = new ResolveInfo();
12647            res.activityInfo = ai;
12648            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12649                res.filter = info;
12650            }
12651            if (info != null) {
12652                res.handleAllWebDataURI = info.handleAllWebDataURI();
12653            }
12654            res.priority = info.getPriority();
12655            res.preferredOrder = activity.owner.mPreferredOrder;
12656            //System.out.println("Result: " + res.activityInfo.className +
12657            //                   " = " + res.priority);
12658            res.match = match;
12659            res.isDefault = info.hasDefault;
12660            res.labelRes = info.labelRes;
12661            res.nonLocalizedLabel = info.nonLocalizedLabel;
12662            if (userNeedsBadging(userId)) {
12663                res.noResourceId = true;
12664            } else {
12665                res.icon = info.icon;
12666            }
12667            res.iconResourceId = info.icon;
12668            res.system = res.activityInfo.applicationInfo.isSystemApp();
12669            res.isInstantAppAvailable = userState.instantApp;
12670            return res;
12671        }
12672
12673        @Override
12674        protected void sortResults(List<ResolveInfo> results) {
12675            Collections.sort(results, mResolvePrioritySorter);
12676        }
12677
12678        @Override
12679        protected void dumpFilter(PrintWriter out, String prefix,
12680                PackageParser.ActivityIntentInfo filter) {
12681            out.print(prefix); out.print(
12682                    Integer.toHexString(System.identityHashCode(filter.activity)));
12683                    out.print(' ');
12684                    filter.activity.printComponentShortName(out);
12685                    out.print(" filter ");
12686                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12687        }
12688
12689        @Override
12690        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12691            return filter.activity;
12692        }
12693
12694        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12695            PackageParser.Activity activity = (PackageParser.Activity)label;
12696            out.print(prefix); out.print(
12697                    Integer.toHexString(System.identityHashCode(activity)));
12698                    out.print(' ');
12699                    activity.printComponentShortName(out);
12700            if (count > 1) {
12701                out.print(" ("); out.print(count); out.print(" filters)");
12702            }
12703            out.println();
12704        }
12705
12706        // Keys are String (activity class name), values are Activity.
12707        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12708                = new ArrayMap<ComponentName, PackageParser.Activity>();
12709        private int mFlags;
12710    }
12711
12712    private final class ServiceIntentResolver
12713            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12714        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12715                boolean defaultOnly, int userId) {
12716            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12717            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12718        }
12719
12720        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12721                int userId) {
12722            if (!sUserManager.exists(userId)) return null;
12723            mFlags = flags;
12724            return super.queryIntent(intent, resolvedType,
12725                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12726                    userId);
12727        }
12728
12729        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12730                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12731            if (!sUserManager.exists(userId)) return null;
12732            if (packageServices == null) {
12733                return null;
12734            }
12735            mFlags = flags;
12736            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12737            final int N = packageServices.size();
12738            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12739                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12740
12741            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12742            for (int i = 0; i < N; ++i) {
12743                intentFilters = packageServices.get(i).intents;
12744                if (intentFilters != null && intentFilters.size() > 0) {
12745                    PackageParser.ServiceIntentInfo[] array =
12746                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12747                    intentFilters.toArray(array);
12748                    listCut.add(array);
12749                }
12750            }
12751            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12752        }
12753
12754        public final void addService(PackageParser.Service s) {
12755            mServices.put(s.getComponentName(), s);
12756            if (DEBUG_SHOW_INFO) {
12757                Log.v(TAG, "  "
12758                        + (s.info.nonLocalizedLabel != null
12759                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12760                Log.v(TAG, "    Class=" + s.info.name);
12761            }
12762            final int NI = s.intents.size();
12763            int j;
12764            for (j=0; j<NI; j++) {
12765                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12766                if (DEBUG_SHOW_INFO) {
12767                    Log.v(TAG, "    IntentFilter:");
12768                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12769                }
12770                if (!intent.debugCheck()) {
12771                    Log.w(TAG, "==> For Service " + s.info.name);
12772                }
12773                addFilter(intent);
12774            }
12775        }
12776
12777        public final void removeService(PackageParser.Service s) {
12778            mServices.remove(s.getComponentName());
12779            if (DEBUG_SHOW_INFO) {
12780                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12781                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12782                Log.v(TAG, "    Class=" + s.info.name);
12783            }
12784            final int NI = s.intents.size();
12785            int j;
12786            for (j=0; j<NI; j++) {
12787                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12788                if (DEBUG_SHOW_INFO) {
12789                    Log.v(TAG, "    IntentFilter:");
12790                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12791                }
12792                removeFilter(intent);
12793            }
12794        }
12795
12796        @Override
12797        protected boolean allowFilterResult(
12798                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12799            ServiceInfo filterSi = filter.service.info;
12800            for (int i=dest.size()-1; i>=0; i--) {
12801                ServiceInfo destAi = dest.get(i).serviceInfo;
12802                if (destAi.name == filterSi.name
12803                        && destAi.packageName == filterSi.packageName) {
12804                    return false;
12805                }
12806            }
12807            return true;
12808        }
12809
12810        @Override
12811        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12812            return new PackageParser.ServiceIntentInfo[size];
12813        }
12814
12815        @Override
12816        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12817            if (!sUserManager.exists(userId)) return true;
12818            PackageParser.Package p = filter.service.owner;
12819            if (p != null) {
12820                PackageSetting ps = (PackageSetting)p.mExtras;
12821                if (ps != null) {
12822                    // System apps are never considered stopped for purposes of
12823                    // filtering, because there may be no way for the user to
12824                    // actually re-launch them.
12825                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12826                            && ps.getStopped(userId);
12827                }
12828            }
12829            return false;
12830        }
12831
12832        @Override
12833        protected boolean isPackageForFilter(String packageName,
12834                PackageParser.ServiceIntentInfo info) {
12835            return packageName.equals(info.service.owner.packageName);
12836        }
12837
12838        @Override
12839        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12840                int match, int userId) {
12841            if (!sUserManager.exists(userId)) return null;
12842            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12843            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12844                return null;
12845            }
12846            final PackageParser.Service service = info.service;
12847            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12848            if (ps == null) {
12849                return null;
12850            }
12851            final PackageUserState userState = ps.readUserState(userId);
12852            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12853                    userState, userId);
12854            if (si == null) {
12855                return null;
12856            }
12857            final boolean matchVisibleToInstantApp =
12858                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12859            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12860            // throw out filters that aren't visible to ephemeral apps
12861            if (matchVisibleToInstantApp
12862                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12863                return null;
12864            }
12865            // throw out ephemeral filters if we're not explicitly requesting them
12866            if (!isInstantApp && userState.instantApp) {
12867                return null;
12868            }
12869            // throw out instant app filters if updates are available; will trigger
12870            // instant app resolution
12871            if (userState.instantApp && ps.isUpdateAvailable()) {
12872                return null;
12873            }
12874            final ResolveInfo res = new ResolveInfo();
12875            res.serviceInfo = si;
12876            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12877                res.filter = filter;
12878            }
12879            res.priority = info.getPriority();
12880            res.preferredOrder = service.owner.mPreferredOrder;
12881            res.match = match;
12882            res.isDefault = info.hasDefault;
12883            res.labelRes = info.labelRes;
12884            res.nonLocalizedLabel = info.nonLocalizedLabel;
12885            res.icon = info.icon;
12886            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12887            return res;
12888        }
12889
12890        @Override
12891        protected void sortResults(List<ResolveInfo> results) {
12892            Collections.sort(results, mResolvePrioritySorter);
12893        }
12894
12895        @Override
12896        protected void dumpFilter(PrintWriter out, String prefix,
12897                PackageParser.ServiceIntentInfo filter) {
12898            out.print(prefix); out.print(
12899                    Integer.toHexString(System.identityHashCode(filter.service)));
12900                    out.print(' ');
12901                    filter.service.printComponentShortName(out);
12902                    out.print(" filter ");
12903                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12904                    if (filter.service.info.permission != null) {
12905                        out.print(" permission "); out.println(filter.service.info.permission);
12906                    } else {
12907                        out.println();
12908                    }
12909        }
12910
12911        @Override
12912        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12913            return filter.service;
12914        }
12915
12916        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12917            PackageParser.Service service = (PackageParser.Service)label;
12918            out.print(prefix); out.print(
12919                    Integer.toHexString(System.identityHashCode(service)));
12920                    out.print(' ');
12921                    service.printComponentShortName(out);
12922            if (count > 1) {
12923                out.print(" ("); out.print(count); out.print(" filters)");
12924            }
12925            out.println();
12926        }
12927
12928//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12929//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12930//            final List<ResolveInfo> retList = Lists.newArrayList();
12931//            while (i.hasNext()) {
12932//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12933//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12934//                    retList.add(resolveInfo);
12935//                }
12936//            }
12937//            return retList;
12938//        }
12939
12940        // Keys are String (activity class name), values are Activity.
12941        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12942                = new ArrayMap<ComponentName, PackageParser.Service>();
12943        private int mFlags;
12944    }
12945
12946    private final class ProviderIntentResolver
12947            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12948        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12949                boolean defaultOnly, int userId) {
12950            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12951            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12952        }
12953
12954        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12955                int userId) {
12956            if (!sUserManager.exists(userId))
12957                return null;
12958            mFlags = flags;
12959            return super.queryIntent(intent, resolvedType,
12960                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12961                    userId);
12962        }
12963
12964        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12965                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12966            if (!sUserManager.exists(userId))
12967                return null;
12968            if (packageProviders == null) {
12969                return null;
12970            }
12971            mFlags = flags;
12972            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12973            final int N = packageProviders.size();
12974            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12975                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12976
12977            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12978            for (int i = 0; i < N; ++i) {
12979                intentFilters = packageProviders.get(i).intents;
12980                if (intentFilters != null && intentFilters.size() > 0) {
12981                    PackageParser.ProviderIntentInfo[] array =
12982                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12983                    intentFilters.toArray(array);
12984                    listCut.add(array);
12985                }
12986            }
12987            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12988        }
12989
12990        public final void addProvider(PackageParser.Provider p) {
12991            if (mProviders.containsKey(p.getComponentName())) {
12992                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12993                return;
12994            }
12995
12996            mProviders.put(p.getComponentName(), p);
12997            if (DEBUG_SHOW_INFO) {
12998                Log.v(TAG, "  "
12999                        + (p.info.nonLocalizedLabel != null
13000                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13001                Log.v(TAG, "    Class=" + p.info.name);
13002            }
13003            final int NI = p.intents.size();
13004            int j;
13005            for (j = 0; j < NI; j++) {
13006                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13007                if (DEBUG_SHOW_INFO) {
13008                    Log.v(TAG, "    IntentFilter:");
13009                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13010                }
13011                if (!intent.debugCheck()) {
13012                    Log.w(TAG, "==> For Provider " + p.info.name);
13013                }
13014                addFilter(intent);
13015            }
13016        }
13017
13018        public final void removeProvider(PackageParser.Provider p) {
13019            mProviders.remove(p.getComponentName());
13020            if (DEBUG_SHOW_INFO) {
13021                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13022                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13023                Log.v(TAG, "    Class=" + p.info.name);
13024            }
13025            final int NI = p.intents.size();
13026            int j;
13027            for (j = 0; j < NI; j++) {
13028                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13029                if (DEBUG_SHOW_INFO) {
13030                    Log.v(TAG, "    IntentFilter:");
13031                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13032                }
13033                removeFilter(intent);
13034            }
13035        }
13036
13037        @Override
13038        protected boolean allowFilterResult(
13039                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13040            ProviderInfo filterPi = filter.provider.info;
13041            for (int i = dest.size() - 1; i >= 0; i--) {
13042                ProviderInfo destPi = dest.get(i).providerInfo;
13043                if (destPi.name == filterPi.name
13044                        && destPi.packageName == filterPi.packageName) {
13045                    return false;
13046                }
13047            }
13048            return true;
13049        }
13050
13051        @Override
13052        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13053            return new PackageParser.ProviderIntentInfo[size];
13054        }
13055
13056        @Override
13057        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13058            if (!sUserManager.exists(userId))
13059                return true;
13060            PackageParser.Package p = filter.provider.owner;
13061            if (p != null) {
13062                PackageSetting ps = (PackageSetting) p.mExtras;
13063                if (ps != null) {
13064                    // System apps are never considered stopped for purposes of
13065                    // filtering, because there may be no way for the user to
13066                    // actually re-launch them.
13067                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13068                            && ps.getStopped(userId);
13069                }
13070            }
13071            return false;
13072        }
13073
13074        @Override
13075        protected boolean isPackageForFilter(String packageName,
13076                PackageParser.ProviderIntentInfo info) {
13077            return packageName.equals(info.provider.owner.packageName);
13078        }
13079
13080        @Override
13081        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13082                int match, int userId) {
13083            if (!sUserManager.exists(userId))
13084                return null;
13085            final PackageParser.ProviderIntentInfo info = filter;
13086            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13087                return null;
13088            }
13089            final PackageParser.Provider provider = info.provider;
13090            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13091            if (ps == null) {
13092                return null;
13093            }
13094            final PackageUserState userState = ps.readUserState(userId);
13095            final boolean matchVisibleToInstantApp =
13096                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13097            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13098            // throw out filters that aren't visible to instant applications
13099            if (matchVisibleToInstantApp
13100                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13101                return null;
13102            }
13103            // throw out instant application filters if we're not explicitly requesting them
13104            if (!isInstantApp && userState.instantApp) {
13105                return null;
13106            }
13107            // throw out instant application filters if updates are available; will trigger
13108            // instant application resolution
13109            if (userState.instantApp && ps.isUpdateAvailable()) {
13110                return null;
13111            }
13112            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13113                    userState, userId);
13114            if (pi == null) {
13115                return null;
13116            }
13117            final ResolveInfo res = new ResolveInfo();
13118            res.providerInfo = pi;
13119            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13120                res.filter = filter;
13121            }
13122            res.priority = info.getPriority();
13123            res.preferredOrder = provider.owner.mPreferredOrder;
13124            res.match = match;
13125            res.isDefault = info.hasDefault;
13126            res.labelRes = info.labelRes;
13127            res.nonLocalizedLabel = info.nonLocalizedLabel;
13128            res.icon = info.icon;
13129            res.system = res.providerInfo.applicationInfo.isSystemApp();
13130            return res;
13131        }
13132
13133        @Override
13134        protected void sortResults(List<ResolveInfo> results) {
13135            Collections.sort(results, mResolvePrioritySorter);
13136        }
13137
13138        @Override
13139        protected void dumpFilter(PrintWriter out, String prefix,
13140                PackageParser.ProviderIntentInfo filter) {
13141            out.print(prefix);
13142            out.print(
13143                    Integer.toHexString(System.identityHashCode(filter.provider)));
13144            out.print(' ');
13145            filter.provider.printComponentShortName(out);
13146            out.print(" filter ");
13147            out.println(Integer.toHexString(System.identityHashCode(filter)));
13148        }
13149
13150        @Override
13151        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13152            return filter.provider;
13153        }
13154
13155        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13156            PackageParser.Provider provider = (PackageParser.Provider)label;
13157            out.print(prefix); out.print(
13158                    Integer.toHexString(System.identityHashCode(provider)));
13159                    out.print(' ');
13160                    provider.printComponentShortName(out);
13161            if (count > 1) {
13162                out.print(" ("); out.print(count); out.print(" filters)");
13163            }
13164            out.println();
13165        }
13166
13167        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13168                = new ArrayMap<ComponentName, PackageParser.Provider>();
13169        private int mFlags;
13170    }
13171
13172    static final class InstantAppIntentResolver
13173            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13174            AuxiliaryResolveInfo.AuxiliaryFilter> {
13175        /**
13176         * The result that has the highest defined order. Ordering applies on a
13177         * per-package basis. Mapping is from package name to Pair of order and
13178         * EphemeralResolveInfo.
13179         * <p>
13180         * NOTE: This is implemented as a field variable for convenience and efficiency.
13181         * By having a field variable, we're able to track filter ordering as soon as
13182         * a non-zero order is defined. Otherwise, multiple loops across the result set
13183         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13184         * this needs to be contained entirely within {@link #filterResults}.
13185         */
13186        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13187
13188        @Override
13189        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13190            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13191        }
13192
13193        @Override
13194        protected boolean isPackageForFilter(String packageName,
13195                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13196            return true;
13197        }
13198
13199        @Override
13200        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13201                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13202            if (!sUserManager.exists(userId)) {
13203                return null;
13204            }
13205            final String packageName = responseObj.resolveInfo.getPackageName();
13206            final Integer order = responseObj.getOrder();
13207            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13208                    mOrderResult.get(packageName);
13209            // ordering is enabled and this item's order isn't high enough
13210            if (lastOrderResult != null && lastOrderResult.first >= order) {
13211                return null;
13212            }
13213            final InstantAppResolveInfo res = responseObj.resolveInfo;
13214            if (order > 0) {
13215                // non-zero order, enable ordering
13216                mOrderResult.put(packageName, new Pair<>(order, res));
13217            }
13218            return responseObj;
13219        }
13220
13221        @Override
13222        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13223            // only do work if ordering is enabled [most of the time it won't be]
13224            if (mOrderResult.size() == 0) {
13225                return;
13226            }
13227            int resultSize = results.size();
13228            for (int i = 0; i < resultSize; i++) {
13229                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13230                final String packageName = info.getPackageName();
13231                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13232                if (savedInfo == null) {
13233                    // package doesn't having ordering
13234                    continue;
13235                }
13236                if (savedInfo.second == info) {
13237                    // circled back to the highest ordered item; remove from order list
13238                    mOrderResult.remove(packageName);
13239                    if (mOrderResult.size() == 0) {
13240                        // no more ordered items
13241                        break;
13242                    }
13243                    continue;
13244                }
13245                // item has a worse order, remove it from the result list
13246                results.remove(i);
13247                resultSize--;
13248                i--;
13249            }
13250        }
13251    }
13252
13253    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13254            new Comparator<ResolveInfo>() {
13255        public int compare(ResolveInfo r1, ResolveInfo r2) {
13256            int v1 = r1.priority;
13257            int v2 = r2.priority;
13258            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13259            if (v1 != v2) {
13260                return (v1 > v2) ? -1 : 1;
13261            }
13262            v1 = r1.preferredOrder;
13263            v2 = r2.preferredOrder;
13264            if (v1 != v2) {
13265                return (v1 > v2) ? -1 : 1;
13266            }
13267            if (r1.isDefault != r2.isDefault) {
13268                return r1.isDefault ? -1 : 1;
13269            }
13270            v1 = r1.match;
13271            v2 = r2.match;
13272            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13273            if (v1 != v2) {
13274                return (v1 > v2) ? -1 : 1;
13275            }
13276            if (r1.system != r2.system) {
13277                return r1.system ? -1 : 1;
13278            }
13279            if (r1.activityInfo != null) {
13280                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13281            }
13282            if (r1.serviceInfo != null) {
13283                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13284            }
13285            if (r1.providerInfo != null) {
13286                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13287            }
13288            return 0;
13289        }
13290    };
13291
13292    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13293            new Comparator<ProviderInfo>() {
13294        public int compare(ProviderInfo p1, ProviderInfo p2) {
13295            final int v1 = p1.initOrder;
13296            final int v2 = p2.initOrder;
13297            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13298        }
13299    };
13300
13301    @Override
13302    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13303            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13304            final int[] userIds, int[] instantUserIds) {
13305        mHandler.post(new Runnable() {
13306            @Override
13307            public void run() {
13308                try {
13309                    final IActivityManager am = ActivityManager.getService();
13310                    if (am == null) return;
13311                    final int[] resolvedUserIds;
13312                    if (userIds == null) {
13313                        resolvedUserIds = am.getRunningUserIds();
13314                    } else {
13315                        resolvedUserIds = userIds;
13316                    }
13317                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13318                            resolvedUserIds, false);
13319                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13320                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13321                                instantUserIds, true);
13322                    }
13323                } catch (RemoteException ex) {
13324                }
13325            }
13326        });
13327    }
13328
13329    @Override
13330    public void notifyPackageAdded(String packageName) {
13331        final PackageListObserver[] observers;
13332        synchronized (mPackages) {
13333            if (mPackageListObservers.size() == 0) {
13334                return;
13335            }
13336            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13337        }
13338        for (int i = observers.length - 1; i >= 0; --i) {
13339            observers[i].onPackageAdded(packageName);
13340        }
13341    }
13342
13343    @Override
13344    public void notifyPackageRemoved(String packageName) {
13345        final PackageListObserver[] observers;
13346        synchronized (mPackages) {
13347            if (mPackageListObservers.size() == 0) {
13348                return;
13349            }
13350            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13351        }
13352        for (int i = observers.length - 1; i >= 0; --i) {
13353            observers[i].onPackageRemoved(packageName);
13354        }
13355    }
13356
13357    /**
13358     * Sends a broadcast for the given action.
13359     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13360     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13361     * the system and applications allowed to see instant applications to receive package
13362     * lifecycle events for instant applications.
13363     */
13364    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13365            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13366            int[] userIds, boolean isInstantApp)
13367                    throws RemoteException {
13368        for (int id : userIds) {
13369            final Intent intent = new Intent(action,
13370                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13371            final String[] requiredPermissions =
13372                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13373            if (extras != null) {
13374                intent.putExtras(extras);
13375            }
13376            if (targetPkg != null) {
13377                intent.setPackage(targetPkg);
13378            }
13379            // Modify the UID when posting to other users
13380            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13381            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13382                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13383                intent.putExtra(Intent.EXTRA_UID, uid);
13384            }
13385            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13386            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13387            if (DEBUG_BROADCASTS) {
13388                RuntimeException here = new RuntimeException("here");
13389                here.fillInStackTrace();
13390                Slog.d(TAG, "Sending to user " + id + ": "
13391                        + intent.toShortString(false, true, false, false)
13392                        + " " + intent.getExtras(), here);
13393            }
13394            am.broadcastIntent(null, intent, null, finishedReceiver,
13395                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13396                    null, finishedReceiver != null, false, id);
13397        }
13398    }
13399
13400    /**
13401     * Check if the external storage media is available. This is true if there
13402     * is a mounted external storage medium or if the external storage is
13403     * emulated.
13404     */
13405    private boolean isExternalMediaAvailable() {
13406        return mMediaMounted || Environment.isExternalStorageEmulated();
13407    }
13408
13409    @Override
13410    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13411        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13412            return null;
13413        }
13414        if (!isExternalMediaAvailable()) {
13415                // If the external storage is no longer mounted at this point,
13416                // the caller may not have been able to delete all of this
13417                // packages files and can not delete any more.  Bail.
13418            return null;
13419        }
13420        synchronized (mPackages) {
13421            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13422            if (lastPackage != null) {
13423                pkgs.remove(lastPackage);
13424            }
13425            if (pkgs.size() > 0) {
13426                return pkgs.get(0);
13427            }
13428        }
13429        return null;
13430    }
13431
13432    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13433        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13434                userId, andCode ? 1 : 0, packageName);
13435        if (mSystemReady) {
13436            msg.sendToTarget();
13437        } else {
13438            if (mPostSystemReadyMessages == null) {
13439                mPostSystemReadyMessages = new ArrayList<>();
13440            }
13441            mPostSystemReadyMessages.add(msg);
13442        }
13443    }
13444
13445    void startCleaningPackages() {
13446        // reader
13447        if (!isExternalMediaAvailable()) {
13448            return;
13449        }
13450        synchronized (mPackages) {
13451            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13452                return;
13453            }
13454        }
13455        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13456        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13457        IActivityManager am = ActivityManager.getService();
13458        if (am != null) {
13459            int dcsUid = -1;
13460            synchronized (mPackages) {
13461                if (!mDefaultContainerWhitelisted) {
13462                    mDefaultContainerWhitelisted = true;
13463                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13464                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13465                }
13466            }
13467            try {
13468                if (dcsUid > 0) {
13469                    am.backgroundWhitelistUid(dcsUid);
13470                }
13471                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13472                        UserHandle.USER_SYSTEM);
13473            } catch (RemoteException e) {
13474            }
13475        }
13476    }
13477
13478    /**
13479     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13480     * it is acting on behalf on an enterprise or the user).
13481     *
13482     * Note that the ordering of the conditionals in this method is important. The checks we perform
13483     * are as follows, in this order:
13484     *
13485     * 1) If the install is being performed by a system app, we can trust the app to have set the
13486     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13487     *    what it is.
13488     * 2) If the install is being performed by a device or profile owner app, the install reason
13489     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13490     *    set the install reason correctly. If the app targets an older SDK version where install
13491     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13492     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13493     * 3) In all other cases, the install is being performed by a regular app that is neither part
13494     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13495     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13496     *    set to enterprise policy and if so, change it to unknown instead.
13497     */
13498    private int fixUpInstallReason(String installerPackageName, int installerUid,
13499            int installReason) {
13500        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13501                == PERMISSION_GRANTED) {
13502            // If the install is being performed by a system app, we trust that app to have set the
13503            // install reason correctly.
13504            return installReason;
13505        }
13506
13507        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13508            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13509        if (dpm != null) {
13510            ComponentName owner = null;
13511            try {
13512                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13513                if (owner == null) {
13514                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13515                }
13516            } catch (RemoteException e) {
13517            }
13518            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13519                // If the install is being performed by a device or profile owner, the install
13520                // reason should be enterprise policy.
13521                return PackageManager.INSTALL_REASON_POLICY;
13522            }
13523        }
13524
13525        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13526            // If the install is being performed by a regular app (i.e. neither system app nor
13527            // device or profile owner), we have no reason to believe that the app is acting on
13528            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13529            // change it to unknown instead.
13530            return PackageManager.INSTALL_REASON_UNKNOWN;
13531        }
13532
13533        // If the install is being performed by a regular app and the install reason was set to any
13534        // value but enterprise policy, leave the install reason unchanged.
13535        return installReason;
13536    }
13537
13538    void installStage(String packageName, File stagedDir,
13539            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13540            String installerPackageName, int installerUid, UserHandle user,
13541            PackageParser.SigningDetails signingDetails) {
13542        if (DEBUG_INSTANT) {
13543            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13544                Slog.d(TAG, "Ephemeral install of " + packageName);
13545            }
13546        }
13547        final VerificationInfo verificationInfo = new VerificationInfo(
13548                sessionParams.originatingUri, sessionParams.referrerUri,
13549                sessionParams.originatingUid, installerUid);
13550
13551        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13552
13553        final Message msg = mHandler.obtainMessage(INIT_COPY);
13554        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13555                sessionParams.installReason);
13556        final InstallParams params = new InstallParams(origin, null, observer,
13557                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13558                verificationInfo, user, sessionParams.abiOverride,
13559                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13560        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13561        msg.obj = params;
13562
13563        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13564                System.identityHashCode(msg.obj));
13565        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13566                System.identityHashCode(msg.obj));
13567
13568        mHandler.sendMessage(msg);
13569    }
13570
13571    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13572            int userId) {
13573        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13574        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13575        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13576        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13577        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13578                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13579
13580        // Send a session commit broadcast
13581        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13582        info.installReason = pkgSetting.getInstallReason(userId);
13583        info.appPackageName = packageName;
13584        sendSessionCommitBroadcast(info, userId);
13585    }
13586
13587    @Override
13588    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13589            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13590        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13591            return;
13592        }
13593        Bundle extras = new Bundle(1);
13594        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13595        final int uid = UserHandle.getUid(
13596                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13597        extras.putInt(Intent.EXTRA_UID, uid);
13598
13599        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13600                packageName, extras, 0, null, null, userIds, instantUserIds);
13601        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13602            mHandler.post(() -> {
13603                        for (int userId : userIds) {
13604                            sendBootCompletedBroadcastToSystemApp(
13605                                    packageName, includeStopped, userId);
13606                        }
13607                    }
13608            );
13609        }
13610    }
13611
13612    /**
13613     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13614     * automatically without needing an explicit launch.
13615     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13616     */
13617    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13618            int userId) {
13619        // If user is not running, the app didn't miss any broadcast
13620        if (!mUserManagerInternal.isUserRunning(userId)) {
13621            return;
13622        }
13623        final IActivityManager am = ActivityManager.getService();
13624        try {
13625            // Deliver LOCKED_BOOT_COMPLETED first
13626            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13627                    .setPackage(packageName);
13628            if (includeStopped) {
13629                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13630            }
13631            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13632            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13633                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13634
13635            // Deliver BOOT_COMPLETED only if user is unlocked
13636            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13637                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13638                if (includeStopped) {
13639                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13640                }
13641                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13642                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13643            }
13644        } catch (RemoteException e) {
13645            throw e.rethrowFromSystemServer();
13646        }
13647    }
13648
13649    @Override
13650    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13651            int userId) {
13652        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13653        PackageSetting pkgSetting;
13654        final int callingUid = Binder.getCallingUid();
13655        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13656                true /* requireFullPermission */, true /* checkShell */,
13657                "setApplicationHiddenSetting for user " + userId);
13658
13659        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13660            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13661            return false;
13662        }
13663
13664        long callingId = Binder.clearCallingIdentity();
13665        try {
13666            boolean sendAdded = false;
13667            boolean sendRemoved = false;
13668            // writer
13669            synchronized (mPackages) {
13670                pkgSetting = mSettings.mPackages.get(packageName);
13671                if (pkgSetting == null) {
13672                    return false;
13673                }
13674                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13675                    return false;
13676                }
13677                // Do not allow "android" is being disabled
13678                if ("android".equals(packageName)) {
13679                    Slog.w(TAG, "Cannot hide package: android");
13680                    return false;
13681                }
13682                // Cannot hide static shared libs as they are considered
13683                // a part of the using app (emulating static linking). Also
13684                // static libs are installed always on internal storage.
13685                PackageParser.Package pkg = mPackages.get(packageName);
13686                if (pkg != null && pkg.staticSharedLibName != null) {
13687                    Slog.w(TAG, "Cannot hide package: " + packageName
13688                            + " providing static shared library: "
13689                            + pkg.staticSharedLibName);
13690                    return false;
13691                }
13692                // Only allow protected packages to hide themselves.
13693                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13694                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13695                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13696                    return false;
13697                }
13698
13699                if (pkgSetting.getHidden(userId) != hidden) {
13700                    pkgSetting.setHidden(hidden, userId);
13701                    mSettings.writePackageRestrictionsLPr(userId);
13702                    if (hidden) {
13703                        sendRemoved = true;
13704                    } else {
13705                        sendAdded = true;
13706                    }
13707                }
13708            }
13709            if (sendAdded) {
13710                sendPackageAddedForUser(packageName, pkgSetting, userId);
13711                return true;
13712            }
13713            if (sendRemoved) {
13714                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13715                        "hiding pkg");
13716                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13717                return true;
13718            }
13719        } finally {
13720            Binder.restoreCallingIdentity(callingId);
13721        }
13722        return false;
13723    }
13724
13725    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13726            int userId) {
13727        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13728        info.removedPackage = packageName;
13729        info.installerPackageName = pkgSetting.installerPackageName;
13730        info.removedUsers = new int[] {userId};
13731        info.broadcastUsers = new int[] {userId};
13732        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13733        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13734    }
13735
13736    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13737        if (pkgList.length > 0) {
13738            Bundle extras = new Bundle(1);
13739            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13740
13741            sendPackageBroadcast(
13742                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13743                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13744                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13745                    new int[] {userId}, null);
13746        }
13747    }
13748
13749    /**
13750     * Returns true if application is not found or there was an error. Otherwise it returns
13751     * the hidden state of the package for the given user.
13752     */
13753    @Override
13754    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13755        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13756        final int callingUid = Binder.getCallingUid();
13757        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13758                true /* requireFullPermission */, false /* checkShell */,
13759                "getApplicationHidden for user " + userId);
13760        PackageSetting ps;
13761        long callingId = Binder.clearCallingIdentity();
13762        try {
13763            // writer
13764            synchronized (mPackages) {
13765                ps = mSettings.mPackages.get(packageName);
13766                if (ps == null) {
13767                    return true;
13768                }
13769                if (filterAppAccessLPr(ps, callingUid, userId)) {
13770                    return true;
13771                }
13772                return ps.getHidden(userId);
13773            }
13774        } finally {
13775            Binder.restoreCallingIdentity(callingId);
13776        }
13777    }
13778
13779    /**
13780     * @hide
13781     */
13782    @Override
13783    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13784            int installReason) {
13785        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13786                null);
13787        PackageSetting pkgSetting;
13788        final int callingUid = Binder.getCallingUid();
13789        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13790                true /* requireFullPermission */, true /* checkShell */,
13791                "installExistingPackage for user " + userId);
13792        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13793            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13794        }
13795
13796        long callingId = Binder.clearCallingIdentity();
13797        try {
13798            boolean installed = false;
13799            final boolean instantApp =
13800                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13801            final boolean fullApp =
13802                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13803
13804            // writer
13805            synchronized (mPackages) {
13806                pkgSetting = mSettings.mPackages.get(packageName);
13807                if (pkgSetting == null) {
13808                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13809                }
13810                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13811                    // only allow the existing package to be used if it's installed as a full
13812                    // application for at least one user
13813                    boolean installAllowed = false;
13814                    for (int checkUserId : sUserManager.getUserIds()) {
13815                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13816                        if (installAllowed) {
13817                            break;
13818                        }
13819                    }
13820                    if (!installAllowed) {
13821                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13822                    }
13823                }
13824                if (!pkgSetting.getInstalled(userId)) {
13825                    pkgSetting.setInstalled(true, userId);
13826                    pkgSetting.setHidden(false, userId);
13827                    pkgSetting.setInstallReason(installReason, userId);
13828                    mSettings.writePackageRestrictionsLPr(userId);
13829                    mSettings.writeKernelMappingLPr(pkgSetting);
13830                    installed = true;
13831                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13832                    // upgrade app from instant to full; we don't allow app downgrade
13833                    installed = true;
13834                }
13835                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13836            }
13837
13838            if (installed) {
13839                if (pkgSetting.pkg != null) {
13840                    synchronized (mInstallLock) {
13841                        // We don't need to freeze for a brand new install
13842                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13843                    }
13844                }
13845                sendPackageAddedForUser(packageName, pkgSetting, userId);
13846                synchronized (mPackages) {
13847                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13848                }
13849            }
13850        } finally {
13851            Binder.restoreCallingIdentity(callingId);
13852        }
13853
13854        return PackageManager.INSTALL_SUCCEEDED;
13855    }
13856
13857    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13858            boolean instantApp, boolean fullApp) {
13859        // no state specified; do nothing
13860        if (!instantApp && !fullApp) {
13861            return;
13862        }
13863        if (userId != UserHandle.USER_ALL) {
13864            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13865                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13866            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13867                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13868            }
13869        } else {
13870            for (int currentUserId : sUserManager.getUserIds()) {
13871                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13872                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13873                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13874                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13875                }
13876            }
13877        }
13878    }
13879
13880    boolean isUserRestricted(int userId, String restrictionKey) {
13881        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13882        if (restrictions.getBoolean(restrictionKey, false)) {
13883            Log.w(TAG, "User is restricted: " + restrictionKey);
13884            return true;
13885        }
13886        return false;
13887    }
13888
13889    @Override
13890    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13891            int userId) {
13892        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13893        final int callingUid = Binder.getCallingUid();
13894        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13895                true /* requireFullPermission */, true /* checkShell */,
13896                "setPackagesSuspended for user " + userId);
13897
13898        if (ArrayUtils.isEmpty(packageNames)) {
13899            return packageNames;
13900        }
13901
13902        // List of package names for whom the suspended state has changed.
13903        List<String> changedPackages = new ArrayList<>(packageNames.length);
13904        // List of package names for whom the suspended state is not set as requested in this
13905        // method.
13906        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13907        long callingId = Binder.clearCallingIdentity();
13908        try {
13909            for (int i = 0; i < packageNames.length; i++) {
13910                String packageName = packageNames[i];
13911                boolean changed = false;
13912                final int appId;
13913                synchronized (mPackages) {
13914                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13915                    if (pkgSetting == null
13916                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13917                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13918                                + "\". Skipping suspending/un-suspending.");
13919                        unactionedPackages.add(packageName);
13920                        continue;
13921                    }
13922                    appId = pkgSetting.appId;
13923                    if (pkgSetting.getSuspended(userId) != suspended) {
13924                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13925                            unactionedPackages.add(packageName);
13926                            continue;
13927                        }
13928                        pkgSetting.setSuspended(suspended, userId);
13929                        mSettings.writePackageRestrictionsLPr(userId);
13930                        changed = true;
13931                        changedPackages.add(packageName);
13932                    }
13933                }
13934
13935                if (changed && suspended) {
13936                    killApplication(packageName, UserHandle.getUid(userId, appId),
13937                            "suspending package");
13938                }
13939            }
13940        } finally {
13941            Binder.restoreCallingIdentity(callingId);
13942        }
13943
13944        if (!changedPackages.isEmpty()) {
13945            sendPackagesSuspendedForUser(changedPackages.toArray(
13946                    new String[changedPackages.size()]), userId, suspended);
13947        }
13948
13949        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13950    }
13951
13952    @Override
13953    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13954        final int callingUid = Binder.getCallingUid();
13955        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13956                true /* requireFullPermission */, false /* checkShell */,
13957                "isPackageSuspendedForUser for user " + userId);
13958        synchronized (mPackages) {
13959            final PackageSetting ps = mSettings.mPackages.get(packageName);
13960            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13961                throw new IllegalArgumentException("Unknown target package: " + packageName);
13962            }
13963            return ps.getSuspended(userId);
13964        }
13965    }
13966
13967    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13968        if (isPackageDeviceAdmin(packageName, userId)) {
13969            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13970                    + "\": has an active device admin");
13971            return false;
13972        }
13973
13974        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13975        if (packageName.equals(activeLauncherPackageName)) {
13976            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13977                    + "\": contains the active launcher");
13978            return false;
13979        }
13980
13981        if (packageName.equals(mRequiredInstallerPackage)) {
13982            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13983                    + "\": required for package installation");
13984            return false;
13985        }
13986
13987        if (packageName.equals(mRequiredUninstallerPackage)) {
13988            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13989                    + "\": required for package uninstallation");
13990            return false;
13991        }
13992
13993        if (packageName.equals(mRequiredVerifierPackage)) {
13994            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13995                    + "\": required for package verification");
13996            return false;
13997        }
13998
13999        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14000            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14001                    + "\": is the default dialer");
14002            return false;
14003        }
14004
14005        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14006            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14007                    + "\": protected package");
14008            return false;
14009        }
14010
14011        // Cannot suspend static shared libs as they are considered
14012        // a part of the using app (emulating static linking). Also
14013        // static libs are installed always on internal storage.
14014        PackageParser.Package pkg = mPackages.get(packageName);
14015        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14016            Slog.w(TAG, "Cannot suspend package: " + packageName
14017                    + " providing static shared library: "
14018                    + pkg.staticSharedLibName);
14019            return false;
14020        }
14021
14022        return true;
14023    }
14024
14025    private String getActiveLauncherPackageName(int userId) {
14026        Intent intent = new Intent(Intent.ACTION_MAIN);
14027        intent.addCategory(Intent.CATEGORY_HOME);
14028        ResolveInfo resolveInfo = resolveIntent(
14029                intent,
14030                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14031                PackageManager.MATCH_DEFAULT_ONLY,
14032                userId);
14033
14034        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14035    }
14036
14037    private String getDefaultDialerPackageName(int userId) {
14038        synchronized (mPackages) {
14039            return mSettings.getDefaultDialerPackageNameLPw(userId);
14040        }
14041    }
14042
14043    @Override
14044    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14045        mContext.enforceCallingOrSelfPermission(
14046                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14047                "Only package verification agents can verify applications");
14048
14049        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14050        final PackageVerificationResponse response = new PackageVerificationResponse(
14051                verificationCode, Binder.getCallingUid());
14052        msg.arg1 = id;
14053        msg.obj = response;
14054        mHandler.sendMessage(msg);
14055    }
14056
14057    @Override
14058    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14059            long millisecondsToDelay) {
14060        mContext.enforceCallingOrSelfPermission(
14061                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14062                "Only package verification agents can extend verification timeouts");
14063
14064        final PackageVerificationState state = mPendingVerification.get(id);
14065        final PackageVerificationResponse response = new PackageVerificationResponse(
14066                verificationCodeAtTimeout, Binder.getCallingUid());
14067
14068        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14069            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14070        }
14071        if (millisecondsToDelay < 0) {
14072            millisecondsToDelay = 0;
14073        }
14074        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14075                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14076            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14077        }
14078
14079        if ((state != null) && !state.timeoutExtended()) {
14080            state.extendTimeout();
14081
14082            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14083            msg.arg1 = id;
14084            msg.obj = response;
14085            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14086        }
14087    }
14088
14089    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14090            int verificationCode, UserHandle user) {
14091        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14092        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14093        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14094        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14095        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14096
14097        mContext.sendBroadcastAsUser(intent, user,
14098                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14099    }
14100
14101    private ComponentName matchComponentForVerifier(String packageName,
14102            List<ResolveInfo> receivers) {
14103        ActivityInfo targetReceiver = null;
14104
14105        final int NR = receivers.size();
14106        for (int i = 0; i < NR; i++) {
14107            final ResolveInfo info = receivers.get(i);
14108            if (info.activityInfo == null) {
14109                continue;
14110            }
14111
14112            if (packageName.equals(info.activityInfo.packageName)) {
14113                targetReceiver = info.activityInfo;
14114                break;
14115            }
14116        }
14117
14118        if (targetReceiver == null) {
14119            return null;
14120        }
14121
14122        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14123    }
14124
14125    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14126            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14127        if (pkgInfo.verifiers.length == 0) {
14128            return null;
14129        }
14130
14131        final int N = pkgInfo.verifiers.length;
14132        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14133        for (int i = 0; i < N; i++) {
14134            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14135
14136            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14137                    receivers);
14138            if (comp == null) {
14139                continue;
14140            }
14141
14142            final int verifierUid = getUidForVerifier(verifierInfo);
14143            if (verifierUid == -1) {
14144                continue;
14145            }
14146
14147            if (DEBUG_VERIFY) {
14148                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14149                        + " with the correct signature");
14150            }
14151            sufficientVerifiers.add(comp);
14152            verificationState.addSufficientVerifier(verifierUid);
14153        }
14154
14155        return sufficientVerifiers;
14156    }
14157
14158    private int getUidForVerifier(VerifierInfo verifierInfo) {
14159        synchronized (mPackages) {
14160            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14161            if (pkg == null) {
14162                return -1;
14163            } else if (pkg.mSigningDetails.signatures.length != 1) {
14164                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14165                        + " has more than one signature; ignoring");
14166                return -1;
14167            }
14168
14169            /*
14170             * If the public key of the package's signature does not match
14171             * our expected public key, then this is a different package and
14172             * we should skip.
14173             */
14174
14175            final byte[] expectedPublicKey;
14176            try {
14177                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14178                final PublicKey publicKey = verifierSig.getPublicKey();
14179                expectedPublicKey = publicKey.getEncoded();
14180            } catch (CertificateException e) {
14181                return -1;
14182            }
14183
14184            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14185
14186            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14187                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14188                        + " does not have the expected public key; ignoring");
14189                return -1;
14190            }
14191
14192            return pkg.applicationInfo.uid;
14193        }
14194    }
14195
14196    @Override
14197    public void finishPackageInstall(int token, boolean didLaunch) {
14198        enforceSystemOrRoot("Only the system is allowed to finish installs");
14199
14200        if (DEBUG_INSTALL) {
14201            Slog.v(TAG, "BM finishing package install for " + token);
14202        }
14203        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14204
14205        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14206        mHandler.sendMessage(msg);
14207    }
14208
14209    /**
14210     * Get the verification agent timeout.  Used for both the APK verifier and the
14211     * intent filter verifier.
14212     *
14213     * @return verification timeout in milliseconds
14214     */
14215    private long getVerificationTimeout() {
14216        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14217                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14218                DEFAULT_VERIFICATION_TIMEOUT);
14219    }
14220
14221    /**
14222     * Get the default verification agent response code.
14223     *
14224     * @return default verification response code
14225     */
14226    private int getDefaultVerificationResponse(UserHandle user) {
14227        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14228            return PackageManager.VERIFICATION_REJECT;
14229        }
14230        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14231                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14232                DEFAULT_VERIFICATION_RESPONSE);
14233    }
14234
14235    /**
14236     * Check whether or not package verification has been enabled.
14237     *
14238     * @return true if verification should be performed
14239     */
14240    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14241        if (!DEFAULT_VERIFY_ENABLE) {
14242            return false;
14243        }
14244
14245        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14246
14247        // Check if installing from ADB
14248        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14249            // Do not run verification in a test harness environment
14250            if (ActivityManager.isRunningInTestHarness()) {
14251                return false;
14252            }
14253            if (ensureVerifyAppsEnabled) {
14254                return true;
14255            }
14256            // Check if the developer does not want package verification for ADB installs
14257            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14258                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14259                return false;
14260            }
14261        } else {
14262            // only when not installed from ADB, skip verification for instant apps when
14263            // the installer and verifier are the same.
14264            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14265                if (mInstantAppInstallerActivity != null
14266                        && mInstantAppInstallerActivity.packageName.equals(
14267                                mRequiredVerifierPackage)) {
14268                    try {
14269                        mContext.getSystemService(AppOpsManager.class)
14270                                .checkPackage(installerUid, mRequiredVerifierPackage);
14271                        if (DEBUG_VERIFY) {
14272                            Slog.i(TAG, "disable verification for instant app");
14273                        }
14274                        return false;
14275                    } catch (SecurityException ignore) { }
14276                }
14277            }
14278        }
14279
14280        if (ensureVerifyAppsEnabled) {
14281            return true;
14282        }
14283
14284        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14285                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14286    }
14287
14288    @Override
14289    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14290            throws RemoteException {
14291        mContext.enforceCallingOrSelfPermission(
14292                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14293                "Only intentfilter verification agents can verify applications");
14294
14295        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14296        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14297                Binder.getCallingUid(), verificationCode, failedDomains);
14298        msg.arg1 = id;
14299        msg.obj = response;
14300        mHandler.sendMessage(msg);
14301    }
14302
14303    @Override
14304    public int getIntentVerificationStatus(String packageName, int userId) {
14305        final int callingUid = Binder.getCallingUid();
14306        if (UserHandle.getUserId(callingUid) != userId) {
14307            mContext.enforceCallingOrSelfPermission(
14308                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14309                    "getIntentVerificationStatus" + userId);
14310        }
14311        if (getInstantAppPackageName(callingUid) != null) {
14312            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14313        }
14314        synchronized (mPackages) {
14315            final PackageSetting ps = mSettings.mPackages.get(packageName);
14316            if (ps == null
14317                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14318                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14319            }
14320            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14321        }
14322    }
14323
14324    @Override
14325    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14326        mContext.enforceCallingOrSelfPermission(
14327                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14328
14329        boolean result = false;
14330        synchronized (mPackages) {
14331            final PackageSetting ps = mSettings.mPackages.get(packageName);
14332            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14333                return false;
14334            }
14335            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14336        }
14337        if (result) {
14338            scheduleWritePackageRestrictionsLocked(userId);
14339        }
14340        return result;
14341    }
14342
14343    @Override
14344    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14345            String packageName) {
14346        final int callingUid = Binder.getCallingUid();
14347        if (getInstantAppPackageName(callingUid) != null) {
14348            return ParceledListSlice.emptyList();
14349        }
14350        synchronized (mPackages) {
14351            final PackageSetting ps = mSettings.mPackages.get(packageName);
14352            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14353                return ParceledListSlice.emptyList();
14354            }
14355            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14356        }
14357    }
14358
14359    @Override
14360    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14361        if (TextUtils.isEmpty(packageName)) {
14362            return ParceledListSlice.emptyList();
14363        }
14364        final int callingUid = Binder.getCallingUid();
14365        final int callingUserId = UserHandle.getUserId(callingUid);
14366        synchronized (mPackages) {
14367            PackageParser.Package pkg = mPackages.get(packageName);
14368            if (pkg == null || pkg.activities == null) {
14369                return ParceledListSlice.emptyList();
14370            }
14371            if (pkg.mExtras == null) {
14372                return ParceledListSlice.emptyList();
14373            }
14374            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14375            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14376                return ParceledListSlice.emptyList();
14377            }
14378            final int count = pkg.activities.size();
14379            ArrayList<IntentFilter> result = new ArrayList<>();
14380            for (int n=0; n<count; n++) {
14381                PackageParser.Activity activity = pkg.activities.get(n);
14382                if (activity.intents != null && activity.intents.size() > 0) {
14383                    result.addAll(activity.intents);
14384                }
14385            }
14386            return new ParceledListSlice<>(result);
14387        }
14388    }
14389
14390    @Override
14391    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14392        mContext.enforceCallingOrSelfPermission(
14393                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14394        if (UserHandle.getCallingUserId() != userId) {
14395            mContext.enforceCallingOrSelfPermission(
14396                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14397        }
14398
14399        synchronized (mPackages) {
14400            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14401            if (packageName != null) {
14402                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14403                        packageName, userId);
14404            }
14405            return result;
14406        }
14407    }
14408
14409    @Override
14410    public String getDefaultBrowserPackageName(int userId) {
14411        if (UserHandle.getCallingUserId() != userId) {
14412            mContext.enforceCallingOrSelfPermission(
14413                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14414        }
14415        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14416            return null;
14417        }
14418        synchronized (mPackages) {
14419            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14420        }
14421    }
14422
14423    /**
14424     * Get the "allow unknown sources" setting.
14425     *
14426     * @return the current "allow unknown sources" setting
14427     */
14428    private int getUnknownSourcesSettings() {
14429        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14430                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14431                -1);
14432    }
14433
14434    @Override
14435    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14436        final int callingUid = Binder.getCallingUid();
14437        if (getInstantAppPackageName(callingUid) != null) {
14438            return;
14439        }
14440        // writer
14441        synchronized (mPackages) {
14442            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14443            if (targetPackageSetting == null
14444                    || filterAppAccessLPr(
14445                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14446                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14447            }
14448
14449            PackageSetting installerPackageSetting;
14450            if (installerPackageName != null) {
14451                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14452                if (installerPackageSetting == null) {
14453                    throw new IllegalArgumentException("Unknown installer package: "
14454                            + installerPackageName);
14455                }
14456            } else {
14457                installerPackageSetting = null;
14458            }
14459
14460            Signature[] callerSignature;
14461            Object obj = mSettings.getUserIdLPr(callingUid);
14462            if (obj != null) {
14463                if (obj instanceof SharedUserSetting) {
14464                    callerSignature =
14465                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14466                } else if (obj instanceof PackageSetting) {
14467                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14468                } else {
14469                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14470                }
14471            } else {
14472                throw new SecurityException("Unknown calling UID: " + callingUid);
14473            }
14474
14475            // Verify: can't set installerPackageName to a package that is
14476            // not signed with the same cert as the caller.
14477            if (installerPackageSetting != null) {
14478                if (compareSignatures(callerSignature,
14479                        installerPackageSetting.signatures.mSigningDetails.signatures)
14480                        != PackageManager.SIGNATURE_MATCH) {
14481                    throw new SecurityException(
14482                            "Caller does not have same cert as new installer package "
14483                            + installerPackageName);
14484                }
14485            }
14486
14487            // Verify: if target already has an installer package, it must
14488            // be signed with the same cert as the caller.
14489            if (targetPackageSetting.installerPackageName != null) {
14490                PackageSetting setting = mSettings.mPackages.get(
14491                        targetPackageSetting.installerPackageName);
14492                // If the currently set package isn't valid, then it's always
14493                // okay to change it.
14494                if (setting != null) {
14495                    if (compareSignatures(callerSignature,
14496                            setting.signatures.mSigningDetails.signatures)
14497                            != PackageManager.SIGNATURE_MATCH) {
14498                        throw new SecurityException(
14499                                "Caller does not have same cert as old installer package "
14500                                + targetPackageSetting.installerPackageName);
14501                    }
14502                }
14503            }
14504
14505            // Okay!
14506            targetPackageSetting.installerPackageName = installerPackageName;
14507            if (installerPackageName != null) {
14508                mSettings.mInstallerPackages.add(installerPackageName);
14509            }
14510            scheduleWriteSettingsLocked();
14511        }
14512    }
14513
14514    @Override
14515    public void setApplicationCategoryHint(String packageName, int categoryHint,
14516            String callerPackageName) {
14517        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14518            throw new SecurityException("Instant applications don't have access to this method");
14519        }
14520        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14521                callerPackageName);
14522        synchronized (mPackages) {
14523            PackageSetting ps = mSettings.mPackages.get(packageName);
14524            if (ps == null) {
14525                throw new IllegalArgumentException("Unknown target package " + packageName);
14526            }
14527            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14528                throw new IllegalArgumentException("Unknown target package " + packageName);
14529            }
14530            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14531                throw new IllegalArgumentException("Calling package " + callerPackageName
14532                        + " is not installer for " + packageName);
14533            }
14534
14535            if (ps.categoryHint != categoryHint) {
14536                ps.categoryHint = categoryHint;
14537                scheduleWriteSettingsLocked();
14538            }
14539        }
14540    }
14541
14542    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14543        // Queue up an async operation since the package installation may take a little while.
14544        mHandler.post(new Runnable() {
14545            public void run() {
14546                mHandler.removeCallbacks(this);
14547                 // Result object to be returned
14548                PackageInstalledInfo res = new PackageInstalledInfo();
14549                res.setReturnCode(currentStatus);
14550                res.uid = -1;
14551                res.pkg = null;
14552                res.removedInfo = null;
14553                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14554                    args.doPreInstall(res.returnCode);
14555                    synchronized (mInstallLock) {
14556                        installPackageTracedLI(args, res);
14557                    }
14558                    args.doPostInstall(res.returnCode, res.uid);
14559                }
14560
14561                // A restore should be performed at this point if (a) the install
14562                // succeeded, (b) the operation is not an update, and (c) the new
14563                // package has not opted out of backup participation.
14564                final boolean update = res.removedInfo != null
14565                        && res.removedInfo.removedPackage != null;
14566                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14567                boolean doRestore = !update
14568                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14569
14570                // Set up the post-install work request bookkeeping.  This will be used
14571                // and cleaned up by the post-install event handling regardless of whether
14572                // there's a restore pass performed.  Token values are >= 1.
14573                int token;
14574                if (mNextInstallToken < 0) mNextInstallToken = 1;
14575                token = mNextInstallToken++;
14576
14577                PostInstallData data = new PostInstallData(args, res);
14578                mRunningInstalls.put(token, data);
14579                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14580
14581                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14582                    // Pass responsibility to the Backup Manager.  It will perform a
14583                    // restore if appropriate, then pass responsibility back to the
14584                    // Package Manager to run the post-install observer callbacks
14585                    // and broadcasts.
14586                    IBackupManager bm = IBackupManager.Stub.asInterface(
14587                            ServiceManager.getService(Context.BACKUP_SERVICE));
14588                    if (bm != null) {
14589                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14590                                + " to BM for possible restore");
14591                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14592                        try {
14593                            // TODO: http://b/22388012
14594                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14595                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14596                            } else {
14597                                doRestore = false;
14598                            }
14599                        } catch (RemoteException e) {
14600                            // can't happen; the backup manager is local
14601                        } catch (Exception e) {
14602                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14603                            doRestore = false;
14604                        }
14605                    } else {
14606                        Slog.e(TAG, "Backup Manager not found!");
14607                        doRestore = false;
14608                    }
14609                }
14610
14611                if (!doRestore) {
14612                    // No restore possible, or the Backup Manager was mysteriously not
14613                    // available -- just fire the post-install work request directly.
14614                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14615
14616                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14617
14618                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14619                    mHandler.sendMessage(msg);
14620                }
14621            }
14622        });
14623    }
14624
14625    /**
14626     * Callback from PackageSettings whenever an app is first transitioned out of the
14627     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14628     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14629     * here whether the app is the target of an ongoing install, and only send the
14630     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14631     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14632     * handling.
14633     */
14634    void notifyFirstLaunch(final String packageName, final String installerPackage,
14635            final int userId) {
14636        // Serialize this with the rest of the install-process message chain.  In the
14637        // restore-at-install case, this Runnable will necessarily run before the
14638        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14639        // are coherent.  In the non-restore case, the app has already completed install
14640        // and been launched through some other means, so it is not in a problematic
14641        // state for observers to see the FIRST_LAUNCH signal.
14642        mHandler.post(new Runnable() {
14643            @Override
14644            public void run() {
14645                for (int i = 0; i < mRunningInstalls.size(); i++) {
14646                    final PostInstallData data = mRunningInstalls.valueAt(i);
14647                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14648                        continue;
14649                    }
14650                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14651                        // right package; but is it for the right user?
14652                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14653                            if (userId == data.res.newUsers[uIndex]) {
14654                                if (DEBUG_BACKUP) {
14655                                    Slog.i(TAG, "Package " + packageName
14656                                            + " being restored so deferring FIRST_LAUNCH");
14657                                }
14658                                return;
14659                            }
14660                        }
14661                    }
14662                }
14663                // didn't find it, so not being restored
14664                if (DEBUG_BACKUP) {
14665                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14666                }
14667                final boolean isInstantApp = isInstantApp(packageName, userId);
14668                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14669                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14670                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14671            }
14672        });
14673    }
14674
14675    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14676            int[] userIds, int[] instantUserIds) {
14677        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14678                installerPkg, null, userIds, instantUserIds);
14679    }
14680
14681    private abstract class HandlerParams {
14682        private static final int MAX_RETRIES = 4;
14683
14684        /**
14685         * Number of times startCopy() has been attempted and had a non-fatal
14686         * error.
14687         */
14688        private int mRetries = 0;
14689
14690        /** User handle for the user requesting the information or installation. */
14691        private final UserHandle mUser;
14692        String traceMethod;
14693        int traceCookie;
14694
14695        HandlerParams(UserHandle user) {
14696            mUser = user;
14697        }
14698
14699        UserHandle getUser() {
14700            return mUser;
14701        }
14702
14703        HandlerParams setTraceMethod(String traceMethod) {
14704            this.traceMethod = traceMethod;
14705            return this;
14706        }
14707
14708        HandlerParams setTraceCookie(int traceCookie) {
14709            this.traceCookie = traceCookie;
14710            return this;
14711        }
14712
14713        final boolean startCopy() {
14714            boolean res;
14715            try {
14716                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14717
14718                if (++mRetries > MAX_RETRIES) {
14719                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14720                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14721                    handleServiceError();
14722                    return false;
14723                } else {
14724                    handleStartCopy();
14725                    res = true;
14726                }
14727            } catch (RemoteException e) {
14728                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14729                mHandler.sendEmptyMessage(MCS_RECONNECT);
14730                res = false;
14731            }
14732            handleReturnCode();
14733            return res;
14734        }
14735
14736        final void serviceError() {
14737            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14738            handleServiceError();
14739            handleReturnCode();
14740        }
14741
14742        abstract void handleStartCopy() throws RemoteException;
14743        abstract void handleServiceError();
14744        abstract void handleReturnCode();
14745    }
14746
14747    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14748        for (File path : paths) {
14749            try {
14750                mcs.clearDirectory(path.getAbsolutePath());
14751            } catch (RemoteException e) {
14752            }
14753        }
14754    }
14755
14756    static class OriginInfo {
14757        /**
14758         * Location where install is coming from, before it has been
14759         * copied/renamed into place. This could be a single monolithic APK
14760         * file, or a cluster directory. This location may be untrusted.
14761         */
14762        final File file;
14763
14764        /**
14765         * Flag indicating that {@link #file} or {@link #cid} has already been
14766         * staged, meaning downstream users don't need to defensively copy the
14767         * contents.
14768         */
14769        final boolean staged;
14770
14771        /**
14772         * Flag indicating that {@link #file} or {@link #cid} is an already
14773         * installed app that is being moved.
14774         */
14775        final boolean existing;
14776
14777        final String resolvedPath;
14778        final File resolvedFile;
14779
14780        static OriginInfo fromNothing() {
14781            return new OriginInfo(null, false, false);
14782        }
14783
14784        static OriginInfo fromUntrustedFile(File file) {
14785            return new OriginInfo(file, false, false);
14786        }
14787
14788        static OriginInfo fromExistingFile(File file) {
14789            return new OriginInfo(file, false, true);
14790        }
14791
14792        static OriginInfo fromStagedFile(File file) {
14793            return new OriginInfo(file, true, false);
14794        }
14795
14796        private OriginInfo(File file, boolean staged, boolean existing) {
14797            this.file = file;
14798            this.staged = staged;
14799            this.existing = existing;
14800
14801            if (file != null) {
14802                resolvedPath = file.getAbsolutePath();
14803                resolvedFile = file;
14804            } else {
14805                resolvedPath = null;
14806                resolvedFile = null;
14807            }
14808        }
14809    }
14810
14811    static class MoveInfo {
14812        final int moveId;
14813        final String fromUuid;
14814        final String toUuid;
14815        final String packageName;
14816        final String dataAppName;
14817        final int appId;
14818        final String seinfo;
14819        final int targetSdkVersion;
14820
14821        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14822                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14823            this.moveId = moveId;
14824            this.fromUuid = fromUuid;
14825            this.toUuid = toUuid;
14826            this.packageName = packageName;
14827            this.dataAppName = dataAppName;
14828            this.appId = appId;
14829            this.seinfo = seinfo;
14830            this.targetSdkVersion = targetSdkVersion;
14831        }
14832    }
14833
14834    static class VerificationInfo {
14835        /** A constant used to indicate that a uid value is not present. */
14836        public static final int NO_UID = -1;
14837
14838        /** URI referencing where the package was downloaded from. */
14839        final Uri originatingUri;
14840
14841        /** HTTP referrer URI associated with the originatingURI. */
14842        final Uri referrer;
14843
14844        /** UID of the application that the install request originated from. */
14845        final int originatingUid;
14846
14847        /** UID of application requesting the install */
14848        final int installerUid;
14849
14850        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14851            this.originatingUri = originatingUri;
14852            this.referrer = referrer;
14853            this.originatingUid = originatingUid;
14854            this.installerUid = installerUid;
14855        }
14856    }
14857
14858    class InstallParams extends HandlerParams {
14859        final OriginInfo origin;
14860        final MoveInfo move;
14861        final IPackageInstallObserver2 observer;
14862        int installFlags;
14863        final String installerPackageName;
14864        final String volumeUuid;
14865        private InstallArgs mArgs;
14866        private int mRet;
14867        final String packageAbiOverride;
14868        final String[] grantedRuntimePermissions;
14869        final VerificationInfo verificationInfo;
14870        final PackageParser.SigningDetails signingDetails;
14871        final int installReason;
14872
14873        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14874                int installFlags, String installerPackageName, String volumeUuid,
14875                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14876                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14877            super(user);
14878            this.origin = origin;
14879            this.move = move;
14880            this.observer = observer;
14881            this.installFlags = installFlags;
14882            this.installerPackageName = installerPackageName;
14883            this.volumeUuid = volumeUuid;
14884            this.verificationInfo = verificationInfo;
14885            this.packageAbiOverride = packageAbiOverride;
14886            this.grantedRuntimePermissions = grantedPermissions;
14887            this.signingDetails = signingDetails;
14888            this.installReason = installReason;
14889        }
14890
14891        @Override
14892        public String toString() {
14893            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14894                    + " file=" + origin.file + "}";
14895        }
14896
14897        private int installLocationPolicy(PackageInfoLite pkgLite) {
14898            String packageName = pkgLite.packageName;
14899            int installLocation = pkgLite.installLocation;
14900            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14901            // reader
14902            synchronized (mPackages) {
14903                // Currently installed package which the new package is attempting to replace or
14904                // null if no such package is installed.
14905                PackageParser.Package installedPkg = mPackages.get(packageName);
14906                // Package which currently owns the data which the new package will own if installed.
14907                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14908                // will be null whereas dataOwnerPkg will contain information about the package
14909                // which was uninstalled while keeping its data.
14910                PackageParser.Package dataOwnerPkg = installedPkg;
14911                if (dataOwnerPkg  == null) {
14912                    PackageSetting ps = mSettings.mPackages.get(packageName);
14913                    if (ps != null) {
14914                        dataOwnerPkg = ps.pkg;
14915                    }
14916                }
14917
14918                if (dataOwnerPkg != null) {
14919                    // If installed, the package will get access to data left on the device by its
14920                    // predecessor. As a security measure, this is permited only if this is not a
14921                    // version downgrade or if the predecessor package is marked as debuggable and
14922                    // a downgrade is explicitly requested.
14923                    //
14924                    // On debuggable platform builds, downgrades are permitted even for
14925                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14926                    // not offer security guarantees and thus it's OK to disable some security
14927                    // mechanisms to make debugging/testing easier on those builds. However, even on
14928                    // debuggable builds downgrades of packages are permitted only if requested via
14929                    // installFlags. This is because we aim to keep the behavior of debuggable
14930                    // platform builds as close as possible to the behavior of non-debuggable
14931                    // platform builds.
14932                    final boolean downgradeRequested =
14933                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14934                    final boolean packageDebuggable =
14935                                (dataOwnerPkg.applicationInfo.flags
14936                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14937                    final boolean downgradePermitted =
14938                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14939                    if (!downgradePermitted) {
14940                        try {
14941                            checkDowngrade(dataOwnerPkg, pkgLite);
14942                        } catch (PackageManagerException e) {
14943                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14944                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14945                        }
14946                    }
14947                }
14948
14949                if (installedPkg != null) {
14950                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14951                        // Check for updated system application.
14952                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14953                            if (onSd) {
14954                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14955                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14956                            }
14957                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14958                        } else {
14959                            if (onSd) {
14960                                // Install flag overrides everything.
14961                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14962                            }
14963                            // If current upgrade specifies particular preference
14964                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14965                                // Application explicitly specified internal.
14966                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14967                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14968                                // App explictly prefers external. Let policy decide
14969                            } else {
14970                                // Prefer previous location
14971                                if (isExternal(installedPkg)) {
14972                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14973                                }
14974                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14975                            }
14976                        }
14977                    } else {
14978                        // Invalid install. Return error code
14979                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14980                    }
14981                }
14982            }
14983            // All the special cases have been taken care of.
14984            // Return result based on recommended install location.
14985            if (onSd) {
14986                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14987            }
14988            return pkgLite.recommendedInstallLocation;
14989        }
14990
14991        /*
14992         * Invoke remote method to get package information and install
14993         * location values. Override install location based on default
14994         * policy if needed and then create install arguments based
14995         * on the install location.
14996         */
14997        public void handleStartCopy() throws RemoteException {
14998            int ret = PackageManager.INSTALL_SUCCEEDED;
14999
15000            // If we're already staged, we've firmly committed to an install location
15001            if (origin.staged) {
15002                if (origin.file != null) {
15003                    installFlags |= PackageManager.INSTALL_INTERNAL;
15004                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15005                } else {
15006                    throw new IllegalStateException("Invalid stage location");
15007                }
15008            }
15009
15010            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15011            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15012            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15013            PackageInfoLite pkgLite = null;
15014
15015            if (onInt && onSd) {
15016                // Check if both bits are set.
15017                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15018                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15019            } else if (onSd && ephemeral) {
15020                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15021                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15022            } else {
15023                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15024                        packageAbiOverride);
15025
15026                if (DEBUG_INSTANT && ephemeral) {
15027                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15028                }
15029
15030                /*
15031                 * If we have too little free space, try to free cache
15032                 * before giving up.
15033                 */
15034                if (!origin.staged && pkgLite.recommendedInstallLocation
15035                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15036                    // TODO: focus freeing disk space on the target device
15037                    final StorageManager storage = StorageManager.from(mContext);
15038                    final long lowThreshold = storage.getStorageLowBytes(
15039                            Environment.getDataDirectory());
15040
15041                    final long sizeBytes = mContainerService.calculateInstalledSize(
15042                            origin.resolvedPath, packageAbiOverride);
15043
15044                    try {
15045                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15046                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15047                                installFlags, packageAbiOverride);
15048                    } catch (InstallerException e) {
15049                        Slog.w(TAG, "Failed to free cache", e);
15050                    }
15051
15052                    /*
15053                     * The cache free must have deleted the file we
15054                     * downloaded to install.
15055                     *
15056                     * TODO: fix the "freeCache" call to not delete
15057                     *       the file we care about.
15058                     */
15059                    if (pkgLite.recommendedInstallLocation
15060                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15061                        pkgLite.recommendedInstallLocation
15062                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15063                    }
15064                }
15065            }
15066
15067            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15068                int loc = pkgLite.recommendedInstallLocation;
15069                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15070                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15071                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15072                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15073                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15074                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15075                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15076                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15077                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15078                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15079                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15080                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15081                } else {
15082                    // Override with defaults if needed.
15083                    loc = installLocationPolicy(pkgLite);
15084                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15085                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15086                    } else if (!onSd && !onInt) {
15087                        // Override install location with flags
15088                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15089                            // Set the flag to install on external media.
15090                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15091                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15092                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15093                            if (DEBUG_INSTANT) {
15094                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15095                            }
15096                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15097                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15098                                    |PackageManager.INSTALL_INTERNAL);
15099                        } else {
15100                            // Make sure the flag for installing on external
15101                            // media is unset
15102                            installFlags |= PackageManager.INSTALL_INTERNAL;
15103                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15104                        }
15105                    }
15106                }
15107            }
15108
15109            final InstallArgs args = createInstallArgs(this);
15110            mArgs = args;
15111
15112            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15113                // TODO: http://b/22976637
15114                // Apps installed for "all" users use the device owner to verify the app
15115                UserHandle verifierUser = getUser();
15116                if (verifierUser == UserHandle.ALL) {
15117                    verifierUser = UserHandle.SYSTEM;
15118                }
15119
15120                /*
15121                 * Determine if we have any installed package verifiers. If we
15122                 * do, then we'll defer to them to verify the packages.
15123                 */
15124                final int requiredUid = mRequiredVerifierPackage == null ? -1
15125                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15126                                verifierUser.getIdentifier());
15127                final int installerUid =
15128                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15129                if (!origin.existing && requiredUid != -1
15130                        && isVerificationEnabled(
15131                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15132                    final Intent verification = new Intent(
15133                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15134                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15135                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15136                            PACKAGE_MIME_TYPE);
15137                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15138
15139                    // Query all live verifiers based on current user state
15140                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15141                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15142                            false /*allowDynamicSplits*/);
15143
15144                    if (DEBUG_VERIFY) {
15145                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15146                                + verification.toString() + " with " + pkgLite.verifiers.length
15147                                + " optional verifiers");
15148                    }
15149
15150                    final int verificationId = mPendingVerificationToken++;
15151
15152                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15153
15154                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15155                            installerPackageName);
15156
15157                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15158                            installFlags);
15159
15160                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15161                            pkgLite.packageName);
15162
15163                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15164                            pkgLite.versionCode);
15165
15166                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15167                            pkgLite.getLongVersionCode());
15168
15169                    if (verificationInfo != null) {
15170                        if (verificationInfo.originatingUri != null) {
15171                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15172                                    verificationInfo.originatingUri);
15173                        }
15174                        if (verificationInfo.referrer != null) {
15175                            verification.putExtra(Intent.EXTRA_REFERRER,
15176                                    verificationInfo.referrer);
15177                        }
15178                        if (verificationInfo.originatingUid >= 0) {
15179                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15180                                    verificationInfo.originatingUid);
15181                        }
15182                        if (verificationInfo.installerUid >= 0) {
15183                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15184                                    verificationInfo.installerUid);
15185                        }
15186                    }
15187
15188                    final PackageVerificationState verificationState = new PackageVerificationState(
15189                            requiredUid, args);
15190
15191                    mPendingVerification.append(verificationId, verificationState);
15192
15193                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15194                            receivers, verificationState);
15195
15196                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15197                    final long idleDuration = getVerificationTimeout();
15198
15199                    /*
15200                     * If any sufficient verifiers were listed in the package
15201                     * manifest, attempt to ask them.
15202                     */
15203                    if (sufficientVerifiers != null) {
15204                        final int N = sufficientVerifiers.size();
15205                        if (N == 0) {
15206                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15207                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15208                        } else {
15209                            for (int i = 0; i < N; i++) {
15210                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15211                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15212                                        verifierComponent.getPackageName(), idleDuration,
15213                                        verifierUser.getIdentifier(), false, "package verifier");
15214
15215                                final Intent sufficientIntent = new Intent(verification);
15216                                sufficientIntent.setComponent(verifierComponent);
15217                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15218                            }
15219                        }
15220                    }
15221
15222                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15223                            mRequiredVerifierPackage, receivers);
15224                    if (ret == PackageManager.INSTALL_SUCCEEDED
15225                            && mRequiredVerifierPackage != null) {
15226                        Trace.asyncTraceBegin(
15227                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15228                        /*
15229                         * Send the intent to the required verification agent,
15230                         * but only start the verification timeout after the
15231                         * target BroadcastReceivers have run.
15232                         */
15233                        verification.setComponent(requiredVerifierComponent);
15234                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15235                                mRequiredVerifierPackage, idleDuration,
15236                                verifierUser.getIdentifier(), false, "package verifier");
15237                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15238                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15239                                new BroadcastReceiver() {
15240                                    @Override
15241                                    public void onReceive(Context context, Intent intent) {
15242                                        final Message msg = mHandler
15243                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15244                                        msg.arg1 = verificationId;
15245                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15246                                    }
15247                                }, null, 0, null, null);
15248
15249                        /*
15250                         * We don't want the copy to proceed until verification
15251                         * succeeds, so null out this field.
15252                         */
15253                        mArgs = null;
15254                    }
15255                } else {
15256                    /*
15257                     * No package verification is enabled, so immediately start
15258                     * the remote call to initiate copy using temporary file.
15259                     */
15260                    ret = args.copyApk(mContainerService, true);
15261                }
15262            }
15263
15264            mRet = ret;
15265        }
15266
15267        @Override
15268        void handleReturnCode() {
15269            // If mArgs is null, then MCS couldn't be reached. When it
15270            // reconnects, it will try again to install. At that point, this
15271            // will succeed.
15272            if (mArgs != null) {
15273                processPendingInstall(mArgs, mRet);
15274            }
15275        }
15276
15277        @Override
15278        void handleServiceError() {
15279            mArgs = createInstallArgs(this);
15280            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15281        }
15282    }
15283
15284    private InstallArgs createInstallArgs(InstallParams params) {
15285        if (params.move != null) {
15286            return new MoveInstallArgs(params);
15287        } else {
15288            return new FileInstallArgs(params);
15289        }
15290    }
15291
15292    /**
15293     * Create args that describe an existing installed package. Typically used
15294     * when cleaning up old installs, or used as a move source.
15295     */
15296    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15297            String resourcePath, String[] instructionSets) {
15298        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15299    }
15300
15301    static abstract class InstallArgs {
15302        /** @see InstallParams#origin */
15303        final OriginInfo origin;
15304        /** @see InstallParams#move */
15305        final MoveInfo move;
15306
15307        final IPackageInstallObserver2 observer;
15308        // Always refers to PackageManager flags only
15309        final int installFlags;
15310        final String installerPackageName;
15311        final String volumeUuid;
15312        final UserHandle user;
15313        final String abiOverride;
15314        final String[] installGrantPermissions;
15315        /** If non-null, drop an async trace when the install completes */
15316        final String traceMethod;
15317        final int traceCookie;
15318        final PackageParser.SigningDetails signingDetails;
15319        final int installReason;
15320
15321        // The list of instruction sets supported by this app. This is currently
15322        // only used during the rmdex() phase to clean up resources. We can get rid of this
15323        // if we move dex files under the common app path.
15324        /* nullable */ String[] instructionSets;
15325
15326        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15327                int installFlags, String installerPackageName, String volumeUuid,
15328                UserHandle user, String[] instructionSets,
15329                String abiOverride, String[] installGrantPermissions,
15330                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15331                int installReason) {
15332            this.origin = origin;
15333            this.move = move;
15334            this.installFlags = installFlags;
15335            this.observer = observer;
15336            this.installerPackageName = installerPackageName;
15337            this.volumeUuid = volumeUuid;
15338            this.user = user;
15339            this.instructionSets = instructionSets;
15340            this.abiOverride = abiOverride;
15341            this.installGrantPermissions = installGrantPermissions;
15342            this.traceMethod = traceMethod;
15343            this.traceCookie = traceCookie;
15344            this.signingDetails = signingDetails;
15345            this.installReason = installReason;
15346        }
15347
15348        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15349        abstract int doPreInstall(int status);
15350
15351        /**
15352         * Rename package into final resting place. All paths on the given
15353         * scanned package should be updated to reflect the rename.
15354         */
15355        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15356        abstract int doPostInstall(int status, int uid);
15357
15358        /** @see PackageSettingBase#codePathString */
15359        abstract String getCodePath();
15360        /** @see PackageSettingBase#resourcePathString */
15361        abstract String getResourcePath();
15362
15363        // Need installer lock especially for dex file removal.
15364        abstract void cleanUpResourcesLI();
15365        abstract boolean doPostDeleteLI(boolean delete);
15366
15367        /**
15368         * Called before the source arguments are copied. This is used mostly
15369         * for MoveParams when it needs to read the source file to put it in the
15370         * destination.
15371         */
15372        int doPreCopy() {
15373            return PackageManager.INSTALL_SUCCEEDED;
15374        }
15375
15376        /**
15377         * Called after the source arguments are copied. This is used mostly for
15378         * MoveParams when it needs to read the source file to put it in the
15379         * destination.
15380         */
15381        int doPostCopy(int uid) {
15382            return PackageManager.INSTALL_SUCCEEDED;
15383        }
15384
15385        protected boolean isFwdLocked() {
15386            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15387        }
15388
15389        protected boolean isExternalAsec() {
15390            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15391        }
15392
15393        protected boolean isEphemeral() {
15394            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15395        }
15396
15397        UserHandle getUser() {
15398            return user;
15399        }
15400    }
15401
15402    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15403        if (!allCodePaths.isEmpty()) {
15404            if (instructionSets == null) {
15405                throw new IllegalStateException("instructionSet == null");
15406            }
15407            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15408            for (String codePath : allCodePaths) {
15409                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15410                    try {
15411                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15412                    } catch (InstallerException ignored) {
15413                    }
15414                }
15415            }
15416        }
15417    }
15418
15419    /**
15420     * Logic to handle installation of non-ASEC applications, including copying
15421     * and renaming logic.
15422     */
15423    class FileInstallArgs extends InstallArgs {
15424        private File codeFile;
15425        private File resourceFile;
15426
15427        // Example topology:
15428        // /data/app/com.example/base.apk
15429        // /data/app/com.example/split_foo.apk
15430        // /data/app/com.example/lib/arm/libfoo.so
15431        // /data/app/com.example/lib/arm64/libfoo.so
15432        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15433
15434        /** New install */
15435        FileInstallArgs(InstallParams params) {
15436            super(params.origin, params.move, params.observer, params.installFlags,
15437                    params.installerPackageName, params.volumeUuid,
15438                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15439                    params.grantedRuntimePermissions,
15440                    params.traceMethod, params.traceCookie, params.signingDetails,
15441                    params.installReason);
15442            if (isFwdLocked()) {
15443                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15444            }
15445        }
15446
15447        /** Existing install */
15448        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15449            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15450                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15451                    PackageManager.INSTALL_REASON_UNKNOWN);
15452            this.codeFile = (codePath != null) ? new File(codePath) : null;
15453            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15454        }
15455
15456        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15457            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15458            try {
15459                return doCopyApk(imcs, temp);
15460            } finally {
15461                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15462            }
15463        }
15464
15465        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15466            if (origin.staged) {
15467                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15468                codeFile = origin.file;
15469                resourceFile = origin.file;
15470                return PackageManager.INSTALL_SUCCEEDED;
15471            }
15472
15473            try {
15474                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15475                final File tempDir =
15476                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15477                codeFile = tempDir;
15478                resourceFile = tempDir;
15479            } catch (IOException e) {
15480                Slog.w(TAG, "Failed to create copy file: " + e);
15481                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15482            }
15483
15484            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15485                @Override
15486                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15487                    if (!FileUtils.isValidExtFilename(name)) {
15488                        throw new IllegalArgumentException("Invalid filename: " + name);
15489                    }
15490                    try {
15491                        final File file = new File(codeFile, name);
15492                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15493                                O_RDWR | O_CREAT, 0644);
15494                        Os.chmod(file.getAbsolutePath(), 0644);
15495                        return new ParcelFileDescriptor(fd);
15496                    } catch (ErrnoException e) {
15497                        throw new RemoteException("Failed to open: " + e.getMessage());
15498                    }
15499                }
15500            };
15501
15502            int ret = PackageManager.INSTALL_SUCCEEDED;
15503            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15504            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15505                Slog.e(TAG, "Failed to copy package");
15506                return ret;
15507            }
15508
15509            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15510            NativeLibraryHelper.Handle handle = null;
15511            try {
15512                handle = NativeLibraryHelper.Handle.create(codeFile);
15513                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15514                        abiOverride);
15515            } catch (IOException e) {
15516                Slog.e(TAG, "Copying native libraries failed", e);
15517                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15518            } finally {
15519                IoUtils.closeQuietly(handle);
15520            }
15521
15522            return ret;
15523        }
15524
15525        int doPreInstall(int status) {
15526            if (status != PackageManager.INSTALL_SUCCEEDED) {
15527                cleanUp();
15528            }
15529            return status;
15530        }
15531
15532        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15533            if (status != PackageManager.INSTALL_SUCCEEDED) {
15534                cleanUp();
15535                return false;
15536            }
15537
15538            final File targetDir = codeFile.getParentFile();
15539            final File beforeCodeFile = codeFile;
15540            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15541
15542            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15543            try {
15544                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15545            } catch (ErrnoException e) {
15546                Slog.w(TAG, "Failed to rename", e);
15547                return false;
15548            }
15549
15550            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15551                Slog.w(TAG, "Failed to restorecon");
15552                return false;
15553            }
15554
15555            // Reflect the rename internally
15556            codeFile = afterCodeFile;
15557            resourceFile = afterCodeFile;
15558
15559            // Reflect the rename in scanned details
15560            try {
15561                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15562            } catch (IOException e) {
15563                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15564                return false;
15565            }
15566            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15567                    afterCodeFile, pkg.baseCodePath));
15568            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15569                    afterCodeFile, pkg.splitCodePaths));
15570
15571            // Reflect the rename in app info
15572            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15573            pkg.setApplicationInfoCodePath(pkg.codePath);
15574            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15575            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15576            pkg.setApplicationInfoResourcePath(pkg.codePath);
15577            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15578            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15579
15580            return true;
15581        }
15582
15583        int doPostInstall(int status, int uid) {
15584            if (status != PackageManager.INSTALL_SUCCEEDED) {
15585                cleanUp();
15586            }
15587            return status;
15588        }
15589
15590        @Override
15591        String getCodePath() {
15592            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15593        }
15594
15595        @Override
15596        String getResourcePath() {
15597            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15598        }
15599
15600        private boolean cleanUp() {
15601            if (codeFile == null || !codeFile.exists()) {
15602                return false;
15603            }
15604
15605            removeCodePathLI(codeFile);
15606
15607            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15608                resourceFile.delete();
15609            }
15610
15611            return true;
15612        }
15613
15614        void cleanUpResourcesLI() {
15615            // Try enumerating all code paths before deleting
15616            List<String> allCodePaths = Collections.EMPTY_LIST;
15617            if (codeFile != null && codeFile.exists()) {
15618                try {
15619                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15620                    allCodePaths = pkg.getAllCodePaths();
15621                } catch (PackageParserException e) {
15622                    // Ignored; we tried our best
15623                }
15624            }
15625
15626            cleanUp();
15627            removeDexFiles(allCodePaths, instructionSets);
15628        }
15629
15630        boolean doPostDeleteLI(boolean delete) {
15631            // XXX err, shouldn't we respect the delete flag?
15632            cleanUpResourcesLI();
15633            return true;
15634        }
15635    }
15636
15637    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15638            PackageManagerException {
15639        if (copyRet < 0) {
15640            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15641                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15642                throw new PackageManagerException(copyRet, message);
15643            }
15644        }
15645    }
15646
15647    /**
15648     * Extract the StorageManagerService "container ID" from the full code path of an
15649     * .apk.
15650     */
15651    static String cidFromCodePath(String fullCodePath) {
15652        int eidx = fullCodePath.lastIndexOf("/");
15653        String subStr1 = fullCodePath.substring(0, eidx);
15654        int sidx = subStr1.lastIndexOf("/");
15655        return subStr1.substring(sidx+1, eidx);
15656    }
15657
15658    /**
15659     * Logic to handle movement of existing installed applications.
15660     */
15661    class MoveInstallArgs extends InstallArgs {
15662        private File codeFile;
15663        private File resourceFile;
15664
15665        /** New install */
15666        MoveInstallArgs(InstallParams params) {
15667            super(params.origin, params.move, params.observer, params.installFlags,
15668                    params.installerPackageName, params.volumeUuid,
15669                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15670                    params.grantedRuntimePermissions,
15671                    params.traceMethod, params.traceCookie, params.signingDetails,
15672                    params.installReason);
15673        }
15674
15675        int copyApk(IMediaContainerService imcs, boolean temp) {
15676            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15677                    + move.fromUuid + " to " + move.toUuid);
15678            synchronized (mInstaller) {
15679                try {
15680                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15681                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15682                } catch (InstallerException e) {
15683                    Slog.w(TAG, "Failed to move app", e);
15684                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15685                }
15686            }
15687
15688            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15689            resourceFile = codeFile;
15690            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15691
15692            return PackageManager.INSTALL_SUCCEEDED;
15693        }
15694
15695        int doPreInstall(int status) {
15696            if (status != PackageManager.INSTALL_SUCCEEDED) {
15697                cleanUp(move.toUuid);
15698            }
15699            return status;
15700        }
15701
15702        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15703            if (status != PackageManager.INSTALL_SUCCEEDED) {
15704                cleanUp(move.toUuid);
15705                return false;
15706            }
15707
15708            // Reflect the move in app info
15709            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15710            pkg.setApplicationInfoCodePath(pkg.codePath);
15711            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15712            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15713            pkg.setApplicationInfoResourcePath(pkg.codePath);
15714            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15715            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15716
15717            return true;
15718        }
15719
15720        int doPostInstall(int status, int uid) {
15721            if (status == PackageManager.INSTALL_SUCCEEDED) {
15722                cleanUp(move.fromUuid);
15723            } else {
15724                cleanUp(move.toUuid);
15725            }
15726            return status;
15727        }
15728
15729        @Override
15730        String getCodePath() {
15731            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15732        }
15733
15734        @Override
15735        String getResourcePath() {
15736            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15737        }
15738
15739        private boolean cleanUp(String volumeUuid) {
15740            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15741                    move.dataAppName);
15742            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15743            final int[] userIds = sUserManager.getUserIds();
15744            synchronized (mInstallLock) {
15745                // Clean up both app data and code
15746                // All package moves are frozen until finished
15747                for (int userId : userIds) {
15748                    try {
15749                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15750                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15751                    } catch (InstallerException e) {
15752                        Slog.w(TAG, String.valueOf(e));
15753                    }
15754                }
15755                removeCodePathLI(codeFile);
15756            }
15757            return true;
15758        }
15759
15760        void cleanUpResourcesLI() {
15761            throw new UnsupportedOperationException();
15762        }
15763
15764        boolean doPostDeleteLI(boolean delete) {
15765            throw new UnsupportedOperationException();
15766        }
15767    }
15768
15769    static String getAsecPackageName(String packageCid) {
15770        int idx = packageCid.lastIndexOf("-");
15771        if (idx == -1) {
15772            return packageCid;
15773        }
15774        return packageCid.substring(0, idx);
15775    }
15776
15777    // Utility method used to create code paths based on package name and available index.
15778    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15779        String idxStr = "";
15780        int idx = 1;
15781        // Fall back to default value of idx=1 if prefix is not
15782        // part of oldCodePath
15783        if (oldCodePath != null) {
15784            String subStr = oldCodePath;
15785            // Drop the suffix right away
15786            if (suffix != null && subStr.endsWith(suffix)) {
15787                subStr = subStr.substring(0, subStr.length() - suffix.length());
15788            }
15789            // If oldCodePath already contains prefix find out the
15790            // ending index to either increment or decrement.
15791            int sidx = subStr.lastIndexOf(prefix);
15792            if (sidx != -1) {
15793                subStr = subStr.substring(sidx + prefix.length());
15794                if (subStr != null) {
15795                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15796                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15797                    }
15798                    try {
15799                        idx = Integer.parseInt(subStr);
15800                        if (idx <= 1) {
15801                            idx++;
15802                        } else {
15803                            idx--;
15804                        }
15805                    } catch(NumberFormatException e) {
15806                    }
15807                }
15808            }
15809        }
15810        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15811        return prefix + idxStr;
15812    }
15813
15814    private File getNextCodePath(File targetDir, String packageName) {
15815        File result;
15816        SecureRandom random = new SecureRandom();
15817        byte[] bytes = new byte[16];
15818        do {
15819            random.nextBytes(bytes);
15820            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15821            result = new File(targetDir, packageName + "-" + suffix);
15822        } while (result.exists());
15823        return result;
15824    }
15825
15826    // Utility method that returns the relative package path with respect
15827    // to the installation directory. Like say for /data/data/com.test-1.apk
15828    // string com.test-1 is returned.
15829    static String deriveCodePathName(String codePath) {
15830        if (codePath == null) {
15831            return null;
15832        }
15833        final File codeFile = new File(codePath);
15834        final String name = codeFile.getName();
15835        if (codeFile.isDirectory()) {
15836            return name;
15837        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15838            final int lastDot = name.lastIndexOf('.');
15839            return name.substring(0, lastDot);
15840        } else {
15841            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15842            return null;
15843        }
15844    }
15845
15846    static class PackageInstalledInfo {
15847        String name;
15848        int uid;
15849        // The set of users that originally had this package installed.
15850        int[] origUsers;
15851        // The set of users that now have this package installed.
15852        int[] newUsers;
15853        PackageParser.Package pkg;
15854        int returnCode;
15855        String returnMsg;
15856        String installerPackageName;
15857        PackageRemovedInfo removedInfo;
15858        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15859
15860        public void setError(int code, String msg) {
15861            setReturnCode(code);
15862            setReturnMessage(msg);
15863            Slog.w(TAG, msg);
15864        }
15865
15866        public void setError(String msg, PackageParserException e) {
15867            setReturnCode(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 setError(String msg, PackageManagerException e) {
15877            returnCode = e.error;
15878            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15879            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15880            for (int i = 0; i < childCount; i++) {
15881                addedChildPackages.valueAt(i).setError(msg, e);
15882            }
15883            Slog.w(TAG, msg, e);
15884        }
15885
15886        public void setReturnCode(int returnCode) {
15887            this.returnCode = returnCode;
15888            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15889            for (int i = 0; i < childCount; i++) {
15890                addedChildPackages.valueAt(i).returnCode = returnCode;
15891            }
15892        }
15893
15894        private void setReturnMessage(String returnMsg) {
15895            this.returnMsg = returnMsg;
15896            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15897            for (int i = 0; i < childCount; i++) {
15898                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15899            }
15900        }
15901
15902        // In some error cases we want to convey more info back to the observer
15903        String origPackage;
15904        String origPermission;
15905    }
15906
15907    /*
15908     * Install a non-existing package.
15909     */
15910    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15911            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15912            String volumeUuid, PackageInstalledInfo res, int installReason) {
15913        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15914
15915        // Remember this for later, in case we need to rollback this install
15916        String pkgName = pkg.packageName;
15917
15918        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15919
15920        synchronized(mPackages) {
15921            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15922            if (renamedPackage != null) {
15923                // A package with the same name is already installed, though
15924                // it has been renamed to an older name.  The package we
15925                // are trying to install should be installed as an update to
15926                // the existing one, but that has not been requested, so bail.
15927                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15928                        + " without first uninstalling package running as "
15929                        + renamedPackage);
15930                return;
15931            }
15932            if (mPackages.containsKey(pkgName)) {
15933                // Don't allow installation over an existing package with the same name.
15934                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15935                        + " without first uninstalling.");
15936                return;
15937            }
15938        }
15939
15940        try {
15941            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15942                    System.currentTimeMillis(), user);
15943
15944            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15945
15946            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15947                prepareAppDataAfterInstallLIF(newPackage);
15948
15949            } else {
15950                // Remove package from internal structures, but keep around any
15951                // data that might have already existed
15952                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15953                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15954            }
15955        } catch (PackageManagerException e) {
15956            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15957        }
15958
15959        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15960    }
15961
15962    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15963        try (DigestInputStream digestStream =
15964                new DigestInputStream(new FileInputStream(file), digest)) {
15965            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15966        }
15967    }
15968
15969    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15970            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15971            PackageInstalledInfo res, int installReason) {
15972        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15973
15974        final PackageParser.Package oldPackage;
15975        final PackageSetting ps;
15976        final String pkgName = pkg.packageName;
15977        final int[] allUsers;
15978        final int[] installedUsers;
15979
15980        synchronized(mPackages) {
15981            oldPackage = mPackages.get(pkgName);
15982            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15983
15984            // don't allow upgrade to target a release SDK from a pre-release SDK
15985            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15986                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15987            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15988                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15989            if (oldTargetsPreRelease
15990                    && !newTargetsPreRelease
15991                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15992                Slog.w(TAG, "Can't install package targeting released sdk");
15993                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15994                return;
15995            }
15996
15997            ps = mSettings.mPackages.get(pkgName);
15998
15999            // verify signatures are valid
16000            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16001            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16002                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16003                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16004                            "New package not signed by keys specified by upgrade-keysets: "
16005                                    + pkgName);
16006                    return;
16007                }
16008            } else {
16009
16010                // default to original signature matching
16011                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16012                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16013                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16014                            "New package has a different signature: " + pkgName);
16015                    return;
16016                }
16017            }
16018
16019            // don't allow a system upgrade unless the upgrade hash matches
16020            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16021                byte[] digestBytes = null;
16022                try {
16023                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16024                    updateDigest(digest, new File(pkg.baseCodePath));
16025                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16026                        for (String path : pkg.splitCodePaths) {
16027                            updateDigest(digest, new File(path));
16028                        }
16029                    }
16030                    digestBytes = digest.digest();
16031                } catch (NoSuchAlgorithmException | IOException e) {
16032                    res.setError(INSTALL_FAILED_INVALID_APK,
16033                            "Could not compute hash: " + pkgName);
16034                    return;
16035                }
16036                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16037                    res.setError(INSTALL_FAILED_INVALID_APK,
16038                            "New package fails restrict-update check: " + pkgName);
16039                    return;
16040                }
16041                // retain upgrade restriction
16042                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16043            }
16044
16045            // Check for shared user id changes
16046            String invalidPackageName =
16047                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16048            if (invalidPackageName != null) {
16049                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16050                        "Package " + invalidPackageName + " tried to change user "
16051                                + oldPackage.mSharedUserId);
16052                return;
16053            }
16054
16055            // check if the new package supports all of the abis which the old package supports
16056            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16057            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16058            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16059                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16060                        "Update to package " + pkgName + " doesn't support multi arch");
16061                return;
16062            }
16063
16064            // In case of rollback, remember per-user/profile install state
16065            allUsers = sUserManager.getUserIds();
16066            installedUsers = ps.queryInstalledUsers(allUsers, true);
16067
16068            // don't allow an upgrade from full to ephemeral
16069            if (isInstantApp) {
16070                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16071                    for (int currentUser : allUsers) {
16072                        if (!ps.getInstantApp(currentUser)) {
16073                            // can't downgrade from full to instant
16074                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16075                                    + " for user: " + currentUser);
16076                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16077                            return;
16078                        }
16079                    }
16080                } else if (!ps.getInstantApp(user.getIdentifier())) {
16081                    // can't downgrade from full to instant
16082                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16083                            + " for user: " + user.getIdentifier());
16084                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16085                    return;
16086                }
16087            }
16088        }
16089
16090        // Update what is removed
16091        res.removedInfo = new PackageRemovedInfo(this);
16092        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16093        res.removedInfo.removedPackage = oldPackage.packageName;
16094        res.removedInfo.installerPackageName = ps.installerPackageName;
16095        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16096        res.removedInfo.isUpdate = true;
16097        res.removedInfo.origUsers = installedUsers;
16098        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16099        for (int i = 0; i < installedUsers.length; i++) {
16100            final int userId = installedUsers[i];
16101            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16102        }
16103
16104        final int childCount = (oldPackage.childPackages != null)
16105                ? oldPackage.childPackages.size() : 0;
16106        for (int i = 0; i < childCount; i++) {
16107            boolean childPackageUpdated = false;
16108            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16109            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16110            if (res.addedChildPackages != null) {
16111                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16112                if (childRes != null) {
16113                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16114                    childRes.removedInfo.removedPackage = childPkg.packageName;
16115                    if (childPs != null) {
16116                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16117                    }
16118                    childRes.removedInfo.isUpdate = true;
16119                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16120                    childPackageUpdated = true;
16121                }
16122            }
16123            if (!childPackageUpdated) {
16124                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16125                childRemovedRes.removedPackage = childPkg.packageName;
16126                if (childPs != null) {
16127                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16128                }
16129                childRemovedRes.isUpdate = false;
16130                childRemovedRes.dataRemoved = true;
16131                synchronized (mPackages) {
16132                    if (childPs != null) {
16133                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16134                    }
16135                }
16136                if (res.removedInfo.removedChildPackages == null) {
16137                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16138                }
16139                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16140            }
16141        }
16142
16143        boolean sysPkg = (isSystemApp(oldPackage));
16144        if (sysPkg) {
16145            // Set the system/privileged/oem/vendor/product flags as needed
16146            final boolean privileged =
16147                    (oldPackage.applicationInfo.privateFlags
16148                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16149            final boolean oem =
16150                    (oldPackage.applicationInfo.privateFlags
16151                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16152            final boolean vendor =
16153                    (oldPackage.applicationInfo.privateFlags
16154                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16155            final boolean product =
16156                    (oldPackage.applicationInfo.privateFlags
16157                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16158            final @ParseFlags int systemParseFlags = parseFlags;
16159            final @ScanFlags int systemScanFlags = scanFlags
16160                    | SCAN_AS_SYSTEM
16161                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16162                    | (oem ? SCAN_AS_OEM : 0)
16163                    | (vendor ? SCAN_AS_VENDOR : 0)
16164                    | (product ? SCAN_AS_PRODUCT : 0);
16165
16166            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16167                    user, allUsers, installerPackageName, res, installReason);
16168        } else {
16169            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16170                    user, allUsers, installerPackageName, res, installReason);
16171        }
16172    }
16173
16174    @Override
16175    public List<String> getPreviousCodePaths(String packageName) {
16176        final int callingUid = Binder.getCallingUid();
16177        final List<String> result = new ArrayList<>();
16178        if (getInstantAppPackageName(callingUid) != null) {
16179            return result;
16180        }
16181        final PackageSetting ps = mSettings.mPackages.get(packageName);
16182        if (ps != null
16183                && ps.oldCodePaths != null
16184                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16185            result.addAll(ps.oldCodePaths);
16186        }
16187        return result;
16188    }
16189
16190    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16191            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16192            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16193            String installerPackageName, PackageInstalledInfo res, int installReason) {
16194        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16195                + deletedPackage);
16196
16197        String pkgName = deletedPackage.packageName;
16198        boolean deletedPkg = true;
16199        boolean addedPkg = false;
16200        boolean updatedSettings = false;
16201        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16202        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16203                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16204
16205        final long origUpdateTime = (pkg.mExtras != null)
16206                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16207
16208        // First delete the existing package while retaining the data directory
16209        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16210                res.removedInfo, true, pkg)) {
16211            // If the existing package wasn't successfully deleted
16212            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16213            deletedPkg = false;
16214        } else {
16215            // Successfully deleted the old package; proceed with replace.
16216
16217            // If deleted package lived in a container, give users a chance to
16218            // relinquish resources before killing.
16219            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16220                if (DEBUG_INSTALL) {
16221                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16222                }
16223                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16224                final ArrayList<String> pkgList = new ArrayList<String>(1);
16225                pkgList.add(deletedPackage.applicationInfo.packageName);
16226                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16227            }
16228
16229            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16230                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16231
16232            try {
16233                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16234                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16235                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16236                        installReason);
16237
16238                // Update the in-memory copy of the previous code paths.
16239                PackageSetting ps = mSettings.mPackages.get(pkgName);
16240                if (!killApp) {
16241                    if (ps.oldCodePaths == null) {
16242                        ps.oldCodePaths = new ArraySet<>();
16243                    }
16244                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16245                    if (deletedPackage.splitCodePaths != null) {
16246                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16247                    }
16248                } else {
16249                    ps.oldCodePaths = null;
16250                }
16251                if (ps.childPackageNames != null) {
16252                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16253                        final String childPkgName = ps.childPackageNames.get(i);
16254                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16255                        childPs.oldCodePaths = ps.oldCodePaths;
16256                    }
16257                }
16258                // set instant app status, but, only if it's explicitly specified
16259                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16260                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16261                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16262                prepareAppDataAfterInstallLIF(newPackage);
16263                addedPkg = true;
16264                mDexManager.notifyPackageUpdated(newPackage.packageName,
16265                        newPackage.baseCodePath, newPackage.splitCodePaths);
16266            } catch (PackageManagerException e) {
16267                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16268            }
16269        }
16270
16271        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16272            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16273
16274            // Revert all internal state mutations and added folders for the failed install
16275            if (addedPkg) {
16276                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16277                        res.removedInfo, true, null);
16278            }
16279
16280            // Restore the old package
16281            if (deletedPkg) {
16282                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16283                File restoreFile = new File(deletedPackage.codePath);
16284                // Parse old package
16285                boolean oldExternal = isExternal(deletedPackage);
16286                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16287                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16288                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16289                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16290                try {
16291                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16292                            null);
16293                } catch (PackageManagerException e) {
16294                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16295                            + e.getMessage());
16296                    return;
16297                }
16298
16299                synchronized (mPackages) {
16300                    // Ensure the installer package name up to date
16301                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16302
16303                    // Update permissions for restored package
16304                    mPermissionManager.updatePermissions(
16305                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16306                            mPermissionCallback);
16307
16308                    mSettings.writeLPr();
16309                }
16310
16311                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16312            }
16313        } else {
16314            synchronized (mPackages) {
16315                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16316                if (ps != null) {
16317                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16318                    if (res.removedInfo.removedChildPackages != null) {
16319                        final int childCount = res.removedInfo.removedChildPackages.size();
16320                        // Iterate in reverse as we may modify the collection
16321                        for (int i = childCount - 1; i >= 0; i--) {
16322                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16323                            if (res.addedChildPackages.containsKey(childPackageName)) {
16324                                res.removedInfo.removedChildPackages.removeAt(i);
16325                            } else {
16326                                PackageRemovedInfo childInfo = res.removedInfo
16327                                        .removedChildPackages.valueAt(i);
16328                                childInfo.removedForAllUsers = mPackages.get(
16329                                        childInfo.removedPackage) == null;
16330                            }
16331                        }
16332                    }
16333                }
16334            }
16335        }
16336    }
16337
16338    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16339            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16340            final @ScanFlags int scanFlags, UserHandle user,
16341            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16342            int installReason) {
16343        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16344                + ", old=" + deletedPackage);
16345
16346        final boolean disabledSystem;
16347
16348        // Remove existing system package
16349        removePackageLI(deletedPackage, true);
16350
16351        synchronized (mPackages) {
16352            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16353        }
16354        if (!disabledSystem) {
16355            // We didn't need to disable the .apk as a current system package,
16356            // which means we are replacing another update that is already
16357            // installed.  We need to make sure to delete the older one's .apk.
16358            res.removedInfo.args = createInstallArgsForExisting(0,
16359                    deletedPackage.applicationInfo.getCodePath(),
16360                    deletedPackage.applicationInfo.getResourcePath(),
16361                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16362        } else {
16363            res.removedInfo.args = null;
16364        }
16365
16366        // Successfully disabled the old package. Now proceed with re-installation
16367        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16368                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16369
16370        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16371        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16372                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16373
16374        PackageParser.Package newPackage = null;
16375        try {
16376            // Add the package to the internal data structures
16377            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16378
16379            // Set the update and install times
16380            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16381            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16382                    System.currentTimeMillis());
16383
16384            // Update the package dynamic state if succeeded
16385            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16386                // Now that the install succeeded make sure we remove data
16387                // directories for any child package the update removed.
16388                final int deletedChildCount = (deletedPackage.childPackages != null)
16389                        ? deletedPackage.childPackages.size() : 0;
16390                final int newChildCount = (newPackage.childPackages != null)
16391                        ? newPackage.childPackages.size() : 0;
16392                for (int i = 0; i < deletedChildCount; i++) {
16393                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16394                    boolean childPackageDeleted = true;
16395                    for (int j = 0; j < newChildCount; j++) {
16396                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16397                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16398                            childPackageDeleted = false;
16399                            break;
16400                        }
16401                    }
16402                    if (childPackageDeleted) {
16403                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16404                                deletedChildPkg.packageName);
16405                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16406                            PackageRemovedInfo removedChildRes = res.removedInfo
16407                                    .removedChildPackages.get(deletedChildPkg.packageName);
16408                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16409                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16410                        }
16411                    }
16412                }
16413
16414                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16415                        installReason);
16416                prepareAppDataAfterInstallLIF(newPackage);
16417
16418                mDexManager.notifyPackageUpdated(newPackage.packageName,
16419                            newPackage.baseCodePath, newPackage.splitCodePaths);
16420            }
16421        } catch (PackageManagerException e) {
16422            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16423            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16424        }
16425
16426        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16427            // Re installation failed. Restore old information
16428            // Remove new pkg information
16429            if (newPackage != null) {
16430                removeInstalledPackageLI(newPackage, true);
16431            }
16432            // Add back the old system package
16433            try {
16434                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16435            } catch (PackageManagerException e) {
16436                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16437            }
16438
16439            synchronized (mPackages) {
16440                if (disabledSystem) {
16441                    enableSystemPackageLPw(deletedPackage);
16442                }
16443
16444                // Ensure the installer package name up to date
16445                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16446
16447                // Update permissions for restored package
16448                mPermissionManager.updatePermissions(
16449                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16450                        mPermissionCallback);
16451
16452                mSettings.writeLPr();
16453            }
16454
16455            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16456                    + " after failed upgrade");
16457        }
16458    }
16459
16460    /**
16461     * Checks whether the parent or any of the child packages have a change shared
16462     * user. For a package to be a valid update the shred users of the parent and
16463     * the children should match. We may later support changing child shared users.
16464     * @param oldPkg The updated package.
16465     * @param newPkg The update package.
16466     * @return The shared user that change between the versions.
16467     */
16468    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16469            PackageParser.Package newPkg) {
16470        // Check parent shared user
16471        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16472            return newPkg.packageName;
16473        }
16474        // Check child shared users
16475        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16476        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16477        for (int i = 0; i < newChildCount; i++) {
16478            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16479            // If this child was present, did it have the same shared user?
16480            for (int j = 0; j < oldChildCount; j++) {
16481                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16482                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16483                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16484                    return newChildPkg.packageName;
16485                }
16486            }
16487        }
16488        return null;
16489    }
16490
16491    private void removeNativeBinariesLI(PackageSetting ps) {
16492        // Remove the lib path for the parent package
16493        if (ps != null) {
16494            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16495            // Remove the lib path for the child packages
16496            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16497            for (int i = 0; i < childCount; i++) {
16498                PackageSetting childPs = null;
16499                synchronized (mPackages) {
16500                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16501                }
16502                if (childPs != null) {
16503                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16504                            .legacyNativeLibraryPathString);
16505                }
16506            }
16507        }
16508    }
16509
16510    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16511        // Enable the parent package
16512        mSettings.enableSystemPackageLPw(pkg.packageName);
16513        // Enable the child packages
16514        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16515        for (int i = 0; i < childCount; i++) {
16516            PackageParser.Package childPkg = pkg.childPackages.get(i);
16517            mSettings.enableSystemPackageLPw(childPkg.packageName);
16518        }
16519    }
16520
16521    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16522            PackageParser.Package newPkg) {
16523        // Disable the parent package (parent always replaced)
16524        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16525        // Disable the child packages
16526        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16527        for (int i = 0; i < childCount; i++) {
16528            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16529            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16530            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16531        }
16532        return disabled;
16533    }
16534
16535    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16536            String installerPackageName) {
16537        // Enable the parent package
16538        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16539        // Enable the child packages
16540        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16541        for (int i = 0; i < childCount; i++) {
16542            PackageParser.Package childPkg = pkg.childPackages.get(i);
16543            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16544        }
16545    }
16546
16547    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16548            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16549        // Update the parent package setting
16550        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16551                res, user, installReason);
16552        // Update the child packages setting
16553        final int childCount = (newPackage.childPackages != null)
16554                ? newPackage.childPackages.size() : 0;
16555        for (int i = 0; i < childCount; i++) {
16556            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16557            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16558            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16559                    childRes.origUsers, childRes, user, installReason);
16560        }
16561    }
16562
16563    private void updateSettingsInternalLI(PackageParser.Package pkg,
16564            String installerPackageName, int[] allUsers, int[] installedForUsers,
16565            PackageInstalledInfo res, UserHandle user, int installReason) {
16566        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16567
16568        String pkgName = pkg.packageName;
16569        synchronized (mPackages) {
16570            //write settings. the installStatus will be incomplete at this stage.
16571            //note that the new package setting would have already been
16572            //added to mPackages. It hasn't been persisted yet.
16573            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16574            // TODO: Remove this write? It's also written at the end of this method
16575            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16576            mSettings.writeLPr();
16577            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16578        }
16579
16580        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16581        synchronized (mPackages) {
16582// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16583            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16584                    mPermissionCallback);
16585            // For system-bundled packages, we assume that installing an upgraded version
16586            // of the package implies that the user actually wants to run that new code,
16587            // so we enable the package.
16588            PackageSetting ps = mSettings.mPackages.get(pkgName);
16589            final int userId = user.getIdentifier();
16590            if (ps != null) {
16591                if (isSystemApp(pkg)) {
16592                    if (DEBUG_INSTALL) {
16593                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16594                    }
16595                    // Enable system package for requested users
16596                    if (res.origUsers != null) {
16597                        for (int origUserId : res.origUsers) {
16598                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16599                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16600                                        origUserId, installerPackageName);
16601                            }
16602                        }
16603                    }
16604                    // Also convey the prior install/uninstall state
16605                    if (allUsers != null && installedForUsers != null) {
16606                        for (int currentUserId : allUsers) {
16607                            final boolean installed = ArrayUtils.contains(
16608                                    installedForUsers, currentUserId);
16609                            if (DEBUG_INSTALL) {
16610                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16611                            }
16612                            ps.setInstalled(installed, currentUserId);
16613                        }
16614                        // these install state changes will be persisted in the
16615                        // upcoming call to mSettings.writeLPr().
16616                    }
16617                }
16618                // It's implied that when a user requests installation, they want the app to be
16619                // installed and enabled.
16620                if (userId != UserHandle.USER_ALL) {
16621                    ps.setInstalled(true, userId);
16622                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16623                } else {
16624                    for (int currentUserId : sUserManager.getUserIds()) {
16625                        ps.setInstalled(true, currentUserId);
16626                        ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId,
16627                                installerPackageName);
16628                    }
16629                }
16630
16631                // When replacing an existing package, preserve the original install reason for all
16632                // users that had the package installed before.
16633                final Set<Integer> previousUserIds = new ArraySet<>();
16634                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16635                    final int installReasonCount = res.removedInfo.installReasons.size();
16636                    for (int i = 0; i < installReasonCount; i++) {
16637                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16638                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16639                        ps.setInstallReason(previousInstallReason, previousUserId);
16640                        previousUserIds.add(previousUserId);
16641                    }
16642                }
16643
16644                // Set install reason for users that are having the package newly installed.
16645                if (userId == UserHandle.USER_ALL) {
16646                    for (int currentUserId : sUserManager.getUserIds()) {
16647                        if (!previousUserIds.contains(currentUserId)) {
16648                            ps.setInstallReason(installReason, currentUserId);
16649                        }
16650                    }
16651                } else if (!previousUserIds.contains(userId)) {
16652                    ps.setInstallReason(installReason, userId);
16653                }
16654                mSettings.writeKernelMappingLPr(ps);
16655            }
16656            res.name = pkgName;
16657            res.uid = pkg.applicationInfo.uid;
16658            res.pkg = pkg;
16659            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16660            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16661            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16662            //to update install status
16663            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16664            mSettings.writeLPr();
16665            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16666        }
16667
16668        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16669    }
16670
16671    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16672        try {
16673            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16674            installPackageLI(args, res);
16675        } finally {
16676            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16677        }
16678    }
16679
16680    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16681        final int installFlags = args.installFlags;
16682        final String installerPackageName = args.installerPackageName;
16683        final String volumeUuid = args.volumeUuid;
16684        final File tmpPackageFile = new File(args.getCodePath());
16685        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16686        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16687                || (args.volumeUuid != null));
16688        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16689        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16690        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16691        final boolean virtualPreload =
16692                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16693        boolean replace = false;
16694        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16695        if (args.move != null) {
16696            // moving a complete application; perform an initial scan on the new install location
16697            scanFlags |= SCAN_INITIAL;
16698        }
16699        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16700            scanFlags |= SCAN_DONT_KILL_APP;
16701        }
16702        if (instantApp) {
16703            scanFlags |= SCAN_AS_INSTANT_APP;
16704        }
16705        if (fullApp) {
16706            scanFlags |= SCAN_AS_FULL_APP;
16707        }
16708        if (virtualPreload) {
16709            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16710        }
16711
16712        // Result object to be returned
16713        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16714        res.installerPackageName = installerPackageName;
16715
16716        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16717
16718        // Sanity check
16719        if (instantApp && (forwardLocked || onExternal)) {
16720            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16721                    + " external=" + onExternal);
16722            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16723            return;
16724        }
16725
16726        // Retrieve PackageSettings and parse package
16727        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16728                | PackageParser.PARSE_ENFORCE_CODE
16729                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16730                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16731                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16732        PackageParser pp = new PackageParser();
16733        pp.setSeparateProcesses(mSeparateProcesses);
16734        pp.setDisplayMetrics(mMetrics);
16735        pp.setCallback(mPackageParserCallback);
16736
16737        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16738        final PackageParser.Package pkg;
16739        try {
16740            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16741            DexMetadataHelper.validatePackageDexMetadata(pkg);
16742        } catch (PackageParserException e) {
16743            res.setError("Failed parse during installPackageLI", e);
16744            return;
16745        } finally {
16746            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16747        }
16748
16749        // Instant apps have several additional install-time checks.
16750        if (instantApp) {
16751            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16752                Slog.w(TAG,
16753                        "Instant app package " + pkg.packageName + " does not target at least O");
16754                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16755                        "Instant app package must target at least O");
16756                return;
16757            }
16758            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16759                Slog.w(TAG, "Instant app package " + pkg.packageName
16760                        + " does not target targetSandboxVersion 2");
16761                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16762                        "Instant app package must use targetSandboxVersion 2");
16763                return;
16764            }
16765            if (pkg.mSharedUserId != null) {
16766                Slog.w(TAG, "Instant app package " + pkg.packageName
16767                        + " may not declare sharedUserId.");
16768                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16769                        "Instant app package may not declare a sharedUserId");
16770                return;
16771            }
16772        }
16773
16774        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16775            // Static shared libraries have synthetic package names
16776            renameStaticSharedLibraryPackage(pkg);
16777
16778            // No static shared libs on external storage
16779            if (onExternal) {
16780                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16781                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16782                        "Packages declaring static-shared libs cannot be updated");
16783                return;
16784            }
16785        }
16786
16787        // If we are installing a clustered package add results for the children
16788        if (pkg.childPackages != null) {
16789            synchronized (mPackages) {
16790                final int childCount = pkg.childPackages.size();
16791                for (int i = 0; i < childCount; i++) {
16792                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16793                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16794                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16795                    childRes.pkg = childPkg;
16796                    childRes.name = childPkg.packageName;
16797                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16798                    if (childPs != null) {
16799                        childRes.origUsers = childPs.queryInstalledUsers(
16800                                sUserManager.getUserIds(), true);
16801                    }
16802                    if ((mPackages.containsKey(childPkg.packageName))) {
16803                        childRes.removedInfo = new PackageRemovedInfo(this);
16804                        childRes.removedInfo.removedPackage = childPkg.packageName;
16805                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16806                    }
16807                    if (res.addedChildPackages == null) {
16808                        res.addedChildPackages = new ArrayMap<>();
16809                    }
16810                    res.addedChildPackages.put(childPkg.packageName, childRes);
16811                }
16812            }
16813        }
16814
16815        // If package doesn't declare API override, mark that we have an install
16816        // time CPU ABI override.
16817        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16818            pkg.cpuAbiOverride = args.abiOverride;
16819        }
16820
16821        String pkgName = res.name = pkg.packageName;
16822        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16823            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16824                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16825                return;
16826            }
16827        }
16828
16829        try {
16830            // either use what we've been given or parse directly from the APK
16831            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16832                pkg.setSigningDetails(args.signingDetails);
16833            } else {
16834                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16835            }
16836        } catch (PackageParserException e) {
16837            res.setError("Failed collect during installPackageLI", e);
16838            return;
16839        }
16840
16841        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16842                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16843            Slog.w(TAG, "Instant app package " + pkg.packageName
16844                    + " is not signed with at least APK Signature Scheme v2");
16845            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16846                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16847            return;
16848        }
16849
16850        // Get rid of all references to package scan path via parser.
16851        pp = null;
16852        String oldCodePath = null;
16853        boolean systemApp = false;
16854        synchronized (mPackages) {
16855            // Check if installing already existing package
16856            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16857                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16858                if (pkg.mOriginalPackages != null
16859                        && pkg.mOriginalPackages.contains(oldName)
16860                        && mPackages.containsKey(oldName)) {
16861                    // This package is derived from an original package,
16862                    // and this device has been updating from that original
16863                    // name.  We must continue using the original name, so
16864                    // rename the new package here.
16865                    pkg.setPackageName(oldName);
16866                    pkgName = pkg.packageName;
16867                    replace = true;
16868                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16869                            + oldName + " pkgName=" + pkgName);
16870                } else if (mPackages.containsKey(pkgName)) {
16871                    // This package, under its official name, already exists
16872                    // on the device; we should replace it.
16873                    replace = true;
16874                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16875                }
16876
16877                // Child packages are installed through the parent package
16878                if (pkg.parentPackage != null) {
16879                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16880                            "Package " + pkg.packageName + " is child of package "
16881                                    + pkg.parentPackage.parentPackage + ". Child packages "
16882                                    + "can be updated only through the parent package.");
16883                    return;
16884                }
16885
16886                if (replace) {
16887                    // Prevent apps opting out from runtime permissions
16888                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16889                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16890                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16891                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16892                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16893                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16894                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16895                                        + " doesn't support runtime permissions but the old"
16896                                        + " target SDK " + oldTargetSdk + " does.");
16897                        return;
16898                    }
16899                    // Prevent persistent apps from being updated
16900                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16901                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16902                                "Package " + oldPackage.packageName + " is a persistent app. "
16903                                        + "Persistent apps are not updateable.");
16904                        return;
16905                    }
16906                    // Prevent apps from downgrading their targetSandbox.
16907                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16908                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16909                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16910                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16911                                "Package " + pkg.packageName + " new target sandbox "
16912                                + newTargetSandbox + " is incompatible with the previous value of"
16913                                + oldTargetSandbox + ".");
16914                        return;
16915                    }
16916
16917                    // Prevent installing of child packages
16918                    if (oldPackage.parentPackage != null) {
16919                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16920                                "Package " + pkg.packageName + " is child of package "
16921                                        + oldPackage.parentPackage + ". Child packages "
16922                                        + "can be updated only through the parent package.");
16923                        return;
16924                    }
16925                }
16926            }
16927
16928            PackageSetting ps = mSettings.mPackages.get(pkgName);
16929            if (ps != null) {
16930                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16931
16932                // Static shared libs have same package with different versions where
16933                // we internally use a synthetic package name to allow multiple versions
16934                // of the same package, therefore we need to compare signatures against
16935                // the package setting for the latest library version.
16936                PackageSetting signatureCheckPs = ps;
16937                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16938                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16939                    if (libraryEntry != null) {
16940                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16941                    }
16942                }
16943
16944                // Quick sanity check that we're signed correctly if updating;
16945                // we'll check this again later when scanning, but we want to
16946                // bail early here before tripping over redefined permissions.
16947                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16948                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16949                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16950                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16951                                + pkg.packageName + " upgrade keys do not match the "
16952                                + "previously installed version");
16953                        return;
16954                    }
16955                } else {
16956                    try {
16957                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16958                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16959                        // We don't care about disabledPkgSetting on install for now.
16960                        final boolean compatMatch = verifySignatures(
16961                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
16962                                compareRecover);
16963                        // The new KeySets will be re-added later in the scanning process.
16964                        if (compatMatch) {
16965                            synchronized (mPackages) {
16966                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16967                            }
16968                        }
16969                    } catch (PackageManagerException e) {
16970                        res.setError(e.error, e.getMessage());
16971                        return;
16972                    }
16973                }
16974
16975                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16976                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16977                    systemApp = (ps.pkg.applicationInfo.flags &
16978                            ApplicationInfo.FLAG_SYSTEM) != 0;
16979                }
16980                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16981            }
16982
16983            int N = pkg.permissions.size();
16984            for (int i = N-1; i >= 0; i--) {
16985                final PackageParser.Permission perm = pkg.permissions.get(i);
16986                final BasePermission bp =
16987                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16988
16989                // Don't allow anyone but the system to define ephemeral permissions.
16990                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16991                        && !systemApp) {
16992                    Slog.w(TAG, "Non-System package " + pkg.packageName
16993                            + " attempting to delcare ephemeral permission "
16994                            + perm.info.name + "; Removing ephemeral.");
16995                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16996                }
16997
16998                // Check whether the newly-scanned package wants to define an already-defined perm
16999                if (bp != null) {
17000                    // If the defining package is signed with our cert, it's okay.  This
17001                    // also includes the "updating the same package" case, of course.
17002                    // "updating same package" could also involve key-rotation.
17003                    final boolean sigsOk;
17004                    final String sourcePackageName = bp.getSourcePackageName();
17005                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17006                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17007                    if (sourcePackageName.equals(pkg.packageName)
17008                            && (ksms.shouldCheckUpgradeKeySetLocked(
17009                                    sourcePackageSetting, scanFlags))) {
17010                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17011                    } else {
17012
17013                        // in the event of signing certificate rotation, we need to see if the
17014                        // package's certificate has rotated from the current one, or if it is an
17015                        // older certificate with which the current is ok with sharing permissions
17016                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17017                                        pkg.mSigningDetails,
17018                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17019                            sigsOk = true;
17020                        } else if (pkg.mSigningDetails.checkCapability(
17021                                        sourcePackageSetting.signatures.mSigningDetails,
17022                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17023
17024                            // the scanned package checks out, has signing certificate rotation
17025                            // history, and is newer; bring it over
17026                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17027                            sigsOk = true;
17028                        } else {
17029                            sigsOk = false;
17030                        }
17031                    }
17032                    if (!sigsOk) {
17033                        // If the owning package is the system itself, we log but allow
17034                        // install to proceed; we fail the install on all other permission
17035                        // redefinitions.
17036                        if (!sourcePackageName.equals("android")) {
17037                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17038                                    + pkg.packageName + " attempting to redeclare permission "
17039                                    + perm.info.name + " already owned by " + sourcePackageName);
17040                            res.origPermission = perm.info.name;
17041                            res.origPackage = sourcePackageName;
17042                            return;
17043                        } else {
17044                            Slog.w(TAG, "Package " + pkg.packageName
17045                                    + " attempting to redeclare system permission "
17046                                    + perm.info.name + "; ignoring new declaration");
17047                            pkg.permissions.remove(i);
17048                        }
17049                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17050                        // Prevent apps to change protection level to dangerous from any other
17051                        // type as this would allow a privilege escalation where an app adds a
17052                        // normal/signature permission in other app's group and later redefines
17053                        // it as dangerous leading to the group auto-grant.
17054                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17055                                == PermissionInfo.PROTECTION_DANGEROUS) {
17056                            if (bp != null && !bp.isRuntime()) {
17057                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17058                                        + "non-runtime permission " + perm.info.name
17059                                        + " to runtime; keeping old protection level");
17060                                perm.info.protectionLevel = bp.getProtectionLevel();
17061                            }
17062                        }
17063                    }
17064                }
17065            }
17066        }
17067
17068        if (systemApp) {
17069            if (onExternal) {
17070                // Abort update; system app can't be replaced with app on sdcard
17071                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17072                        "Cannot install updates to system apps on sdcard");
17073                return;
17074            } else if (instantApp) {
17075                // Abort update; system app can't be replaced with an instant app
17076                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17077                        "Cannot update a system app with an instant app");
17078                return;
17079            }
17080        }
17081
17082        if (args.move != null) {
17083            // We did an in-place move, so dex is ready to roll
17084            scanFlags |= SCAN_NO_DEX;
17085            scanFlags |= SCAN_MOVE;
17086
17087            synchronized (mPackages) {
17088                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17089                if (ps == null) {
17090                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17091                            "Missing settings for moved package " + pkgName);
17092                }
17093
17094                // We moved the entire application as-is, so bring over the
17095                // previously derived ABI information.
17096                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17097                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17098            }
17099
17100        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17101            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17102            scanFlags |= SCAN_NO_DEX;
17103
17104            try {
17105                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17106                    args.abiOverride : pkg.cpuAbiOverride);
17107                final boolean extractNativeLibs = !pkg.isLibrary();
17108                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17109            } catch (PackageManagerException pme) {
17110                Slog.e(TAG, "Error deriving application ABI", pme);
17111                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17112                return;
17113            }
17114
17115            // Shared libraries for the package need to be updated.
17116            synchronized (mPackages) {
17117                try {
17118                    updateSharedLibrariesLPr(pkg, null);
17119                } catch (PackageManagerException e) {
17120                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17121                }
17122            }
17123        }
17124
17125        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17126            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17127            return;
17128        }
17129
17130        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17131            String apkPath = null;
17132            synchronized (mPackages) {
17133                // Note that if the attacker managed to skip verify setup, for example by tampering
17134                // with the package settings, upon reboot we will do full apk verification when
17135                // verity is not detected.
17136                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17137                if (ps != null && ps.isPrivileged()) {
17138                    apkPath = pkg.baseCodePath;
17139                }
17140            }
17141
17142            if (apkPath != null) {
17143                final VerityUtils.SetupResult result =
17144                        VerityUtils.generateApkVeritySetupData(apkPath);
17145                if (result.isOk()) {
17146                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17147                    FileDescriptor fd = result.getUnownedFileDescriptor();
17148                    try {
17149                        mInstaller.installApkVerity(apkPath, fd);
17150                    } catch (InstallerException e) {
17151                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17152                                "Failed to set up verity: " + e);
17153                        return;
17154                    } finally {
17155                        IoUtils.closeQuietly(fd);
17156                    }
17157                } else if (result.isFailed()) {
17158                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17159                    return;
17160                } else {
17161                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17162                    // reboot.
17163                }
17164            }
17165        }
17166
17167        if (!instantApp) {
17168            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17169        } else {
17170            if (DEBUG_DOMAIN_VERIFICATION) {
17171                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17172            }
17173        }
17174
17175        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17176                "installPackageLI")) {
17177            if (replace) {
17178                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17179                    // Static libs have a synthetic package name containing the version
17180                    // and cannot be updated as an update would get a new package name,
17181                    // unless this is the exact same version code which is useful for
17182                    // development.
17183                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17184                    if (existingPkg != null &&
17185                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17186                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17187                                + "static-shared libs cannot be updated");
17188                        return;
17189                    }
17190                }
17191                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17192                        installerPackageName, res, args.installReason);
17193            } else {
17194                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17195                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17196            }
17197        }
17198
17199        // Prepare the application profiles for the new code paths.
17200        // This needs to be done before invoking dexopt so that any install-time profile
17201        // can be used for optimizations.
17202        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17203
17204        // Check whether we need to dexopt the app.
17205        //
17206        // NOTE: it is IMPORTANT to call dexopt:
17207        //   - after doRename which will sync the package data from PackageParser.Package and its
17208        //     corresponding ApplicationInfo.
17209        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17210        //     uid of the application (pkg.applicationInfo.uid).
17211        //     This update happens in place!
17212        //
17213        // We only need to dexopt if the package meets ALL of the following conditions:
17214        //   1) it is not forward locked.
17215        //   2) it is not on on an external ASEC container.
17216        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17217        //
17218        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17219        // complete, so we skip this step during installation. Instead, we'll take extra time
17220        // the first time the instant app starts. It's preferred to do it this way to provide
17221        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17222        // middle of running an instant app. The default behaviour can be overridden
17223        // via gservices.
17224        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17225                && !forwardLocked
17226                && !pkg.applicationInfo.isExternalAsec()
17227                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17228                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17229
17230        if (performDexopt) {
17231            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17232            // Do not run PackageDexOptimizer through the local performDexOpt
17233            // method because `pkg` may not be in `mPackages` yet.
17234            //
17235            // Also, don't fail application installs if the dexopt step fails.
17236            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17237                    REASON_INSTALL,
17238                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17239                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17240            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17241                    null /* instructionSets */,
17242                    getOrCreateCompilerPackageStats(pkg),
17243                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17244                    dexoptOptions);
17245            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17246        }
17247
17248        // Notify BackgroundDexOptService that the package has been changed.
17249        // If this is an update of a package which used to fail to compile,
17250        // BackgroundDexOptService will remove it from its blacklist.
17251        // TODO: Layering violation
17252        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17253
17254        synchronized (mPackages) {
17255            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17256            if (ps != null) {
17257                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17258                ps.setUpdateAvailable(false /*updateAvailable*/);
17259            }
17260
17261            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17262            for (int i = 0; i < childCount; i++) {
17263                PackageParser.Package childPkg = pkg.childPackages.get(i);
17264                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17265                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17266                if (childPs != null) {
17267                    childRes.newUsers = childPs.queryInstalledUsers(
17268                            sUserManager.getUserIds(), true);
17269                }
17270            }
17271
17272            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17273                updateSequenceNumberLP(ps, res.newUsers);
17274                updateInstantAppInstallerLocked(pkgName);
17275            }
17276        }
17277    }
17278
17279    private void startIntentFilterVerifications(int userId, boolean replacing,
17280            PackageParser.Package pkg) {
17281        if (mIntentFilterVerifierComponent == null) {
17282            Slog.w(TAG, "No IntentFilter verification will not be done as "
17283                    + "there is no IntentFilterVerifier available!");
17284            return;
17285        }
17286
17287        final int verifierUid = getPackageUid(
17288                mIntentFilterVerifierComponent.getPackageName(),
17289                MATCH_DEBUG_TRIAGED_MISSING,
17290                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17291
17292        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17293        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17294        mHandler.sendMessage(msg);
17295
17296        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17297        for (int i = 0; i < childCount; i++) {
17298            PackageParser.Package childPkg = pkg.childPackages.get(i);
17299            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17300            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17301            mHandler.sendMessage(msg);
17302        }
17303    }
17304
17305    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17306            PackageParser.Package pkg) {
17307        int size = pkg.activities.size();
17308        if (size == 0) {
17309            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17310                    "No activity, so no need to verify any IntentFilter!");
17311            return;
17312        }
17313
17314        final boolean hasDomainURLs = hasDomainURLs(pkg);
17315        if (!hasDomainURLs) {
17316            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17317                    "No domain URLs, so no need to verify any IntentFilter!");
17318            return;
17319        }
17320
17321        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17322                + " if any IntentFilter from the " + size
17323                + " Activities needs verification ...");
17324
17325        int count = 0;
17326        final String packageName = pkg.packageName;
17327
17328        synchronized (mPackages) {
17329            // If this is a new install and we see that we've already run verification for this
17330            // package, we have nothing to do: it means the state was restored from backup.
17331            if (!replacing) {
17332                IntentFilterVerificationInfo ivi =
17333                        mSettings.getIntentFilterVerificationLPr(packageName);
17334                if (ivi != null) {
17335                    if (DEBUG_DOMAIN_VERIFICATION) {
17336                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17337                                + ivi.getStatusString());
17338                    }
17339                    return;
17340                }
17341            }
17342
17343            // If any filters need to be verified, then all need to be.
17344            boolean needToVerify = false;
17345            for (PackageParser.Activity a : pkg.activities) {
17346                for (ActivityIntentInfo filter : a.intents) {
17347                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17348                        if (DEBUG_DOMAIN_VERIFICATION) {
17349                            Slog.d(TAG,
17350                                    "Intent filter needs verification, so processing all filters");
17351                        }
17352                        needToVerify = true;
17353                        break;
17354                    }
17355                }
17356            }
17357
17358            if (needToVerify) {
17359                final int verificationId = mIntentFilterVerificationToken++;
17360                for (PackageParser.Activity a : pkg.activities) {
17361                    for (ActivityIntentInfo filter : a.intents) {
17362                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17363                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17364                                    "Verification needed for IntentFilter:" + filter.toString());
17365                            mIntentFilterVerifier.addOneIntentFilterVerification(
17366                                    verifierUid, userId, verificationId, filter, packageName);
17367                            count++;
17368                        }
17369                    }
17370                }
17371            }
17372        }
17373
17374        if (count > 0) {
17375            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17376                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17377                    +  " for userId:" + userId);
17378            mIntentFilterVerifier.startVerifications(userId);
17379        } else {
17380            if (DEBUG_DOMAIN_VERIFICATION) {
17381                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17382            }
17383        }
17384    }
17385
17386    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17387        final ComponentName cn  = filter.activity.getComponentName();
17388        final String packageName = cn.getPackageName();
17389
17390        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17391                packageName);
17392        if (ivi == null) {
17393            return true;
17394        }
17395        int status = ivi.getStatus();
17396        switch (status) {
17397            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17398            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17399                return true;
17400
17401            default:
17402                // Nothing to do
17403                return false;
17404        }
17405    }
17406
17407    private static boolean isMultiArch(ApplicationInfo info) {
17408        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17409    }
17410
17411    private static boolean isExternal(PackageParser.Package pkg) {
17412        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17413    }
17414
17415    private static boolean isExternal(PackageSetting ps) {
17416        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17417    }
17418
17419    private static boolean isSystemApp(PackageParser.Package pkg) {
17420        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17421    }
17422
17423    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17424        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17425    }
17426
17427    private static boolean isOemApp(PackageParser.Package pkg) {
17428        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17429    }
17430
17431    private static boolean isVendorApp(PackageParser.Package pkg) {
17432        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17433    }
17434
17435    private static boolean isProductApp(PackageParser.Package pkg) {
17436        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17437    }
17438
17439    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17440        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17441    }
17442
17443    private static boolean isSystemApp(PackageSetting ps) {
17444        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17445    }
17446
17447    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17448        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17449    }
17450
17451    private int packageFlagsToInstallFlags(PackageSetting ps) {
17452        int installFlags = 0;
17453        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17454            // This existing package was an external ASEC install when we have
17455            // the external flag without a UUID
17456            installFlags |= PackageManager.INSTALL_EXTERNAL;
17457        }
17458        if (ps.isForwardLocked()) {
17459            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17460        }
17461        return installFlags;
17462    }
17463
17464    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17465        if (isExternal(pkg)) {
17466            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17467                return mSettings.getExternalVersion();
17468            } else {
17469                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17470            }
17471        } else {
17472            return mSettings.getInternalVersion();
17473        }
17474    }
17475
17476    private void deleteTempPackageFiles() {
17477        final FilenameFilter filter = new FilenameFilter() {
17478            public boolean accept(File dir, String name) {
17479                return name.startsWith("vmdl") && name.endsWith(".tmp");
17480            }
17481        };
17482        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17483            file.delete();
17484        }
17485    }
17486
17487    @Override
17488    public void deletePackageAsUser(String packageName, int versionCode,
17489            IPackageDeleteObserver observer, int userId, int flags) {
17490        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17491                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17492    }
17493
17494    @Override
17495    public void deletePackageVersioned(VersionedPackage versionedPackage,
17496            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17497        final int callingUid = Binder.getCallingUid();
17498        mContext.enforceCallingOrSelfPermission(
17499                android.Manifest.permission.DELETE_PACKAGES, null);
17500        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17501        Preconditions.checkNotNull(versionedPackage);
17502        Preconditions.checkNotNull(observer);
17503        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17504                PackageManager.VERSION_CODE_HIGHEST,
17505                Long.MAX_VALUE, "versionCode must be >= -1");
17506
17507        final String packageName = versionedPackage.getPackageName();
17508        final long versionCode = versionedPackage.getLongVersionCode();
17509        final String internalPackageName;
17510        synchronized (mPackages) {
17511            // Normalize package name to handle renamed packages and static libs
17512            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17513        }
17514
17515        final int uid = Binder.getCallingUid();
17516        if (!isOrphaned(internalPackageName)
17517                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17518            try {
17519                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17520                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17521                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17522                observer.onUserActionRequired(intent);
17523            } catch (RemoteException re) {
17524            }
17525            return;
17526        }
17527        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17528        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17529        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17530            mContext.enforceCallingOrSelfPermission(
17531                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17532                    "deletePackage for user " + userId);
17533        }
17534
17535        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17536            try {
17537                observer.onPackageDeleted(packageName,
17538                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17539            } catch (RemoteException re) {
17540            }
17541            return;
17542        }
17543
17544        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17545            try {
17546                observer.onPackageDeleted(packageName,
17547                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17548            } catch (RemoteException re) {
17549            }
17550            return;
17551        }
17552
17553        if (DEBUG_REMOVE) {
17554            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17555                    + " deleteAllUsers: " + deleteAllUsers + " version="
17556                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17557                    ? "VERSION_CODE_HIGHEST" : versionCode));
17558        }
17559        // Queue up an async operation since the package deletion may take a little while.
17560        mHandler.post(new Runnable() {
17561            public void run() {
17562                mHandler.removeCallbacks(this);
17563                int returnCode;
17564                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17565                boolean doDeletePackage = true;
17566                if (ps != null) {
17567                    final boolean targetIsInstantApp =
17568                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17569                    doDeletePackage = !targetIsInstantApp
17570                            || canViewInstantApps;
17571                }
17572                if (doDeletePackage) {
17573                    if (!deleteAllUsers) {
17574                        returnCode = deletePackageX(internalPackageName, versionCode,
17575                                userId, deleteFlags);
17576                    } else {
17577                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17578                                internalPackageName, users);
17579                        // If nobody is blocking uninstall, proceed with delete for all users
17580                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17581                            returnCode = deletePackageX(internalPackageName, versionCode,
17582                                    userId, deleteFlags);
17583                        } else {
17584                            // Otherwise uninstall individually for users with blockUninstalls=false
17585                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17586                            for (int userId : users) {
17587                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17588                                    returnCode = deletePackageX(internalPackageName, versionCode,
17589                                            userId, userFlags);
17590                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17591                                        Slog.w(TAG, "Package delete failed for user " + userId
17592                                                + ", returnCode " + returnCode);
17593                                    }
17594                                }
17595                            }
17596                            // The app has only been marked uninstalled for certain users.
17597                            // We still need to report that delete was blocked
17598                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17599                        }
17600                    }
17601                } else {
17602                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17603                }
17604                try {
17605                    observer.onPackageDeleted(packageName, returnCode, null);
17606                } catch (RemoteException e) {
17607                    Log.i(TAG, "Observer no longer exists.");
17608                } //end catch
17609            } //end run
17610        });
17611    }
17612
17613    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17614        if (pkg.staticSharedLibName != null) {
17615            return pkg.manifestPackageName;
17616        }
17617        return pkg.packageName;
17618    }
17619
17620    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17621        // Handle renamed packages
17622        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17623        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17624
17625        // Is this a static library?
17626        LongSparseArray<SharedLibraryEntry> versionedLib =
17627                mStaticLibsByDeclaringPackage.get(packageName);
17628        if (versionedLib == null || versionedLib.size() <= 0) {
17629            return packageName;
17630        }
17631
17632        // Figure out which lib versions the caller can see
17633        LongSparseLongArray versionsCallerCanSee = null;
17634        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17635        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17636                && callingAppId != Process.ROOT_UID) {
17637            versionsCallerCanSee = new LongSparseLongArray();
17638            String libName = versionedLib.valueAt(0).info.getName();
17639            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17640            if (uidPackages != null) {
17641                for (String uidPackage : uidPackages) {
17642                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17643                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17644                    if (libIdx >= 0) {
17645                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17646                        versionsCallerCanSee.append(libVersion, libVersion);
17647                    }
17648                }
17649            }
17650        }
17651
17652        // Caller can see nothing - done
17653        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17654            return packageName;
17655        }
17656
17657        // Find the version the caller can see and the app version code
17658        SharedLibraryEntry highestVersion = null;
17659        final int versionCount = versionedLib.size();
17660        for (int i = 0; i < versionCount; i++) {
17661            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17662            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17663                    libEntry.info.getLongVersion()) < 0) {
17664                continue;
17665            }
17666            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17667            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17668                if (libVersionCode == versionCode) {
17669                    return libEntry.apk;
17670                }
17671            } else if (highestVersion == null) {
17672                highestVersion = libEntry;
17673            } else if (libVersionCode  > highestVersion.info
17674                    .getDeclaringPackage().getLongVersionCode()) {
17675                highestVersion = libEntry;
17676            }
17677        }
17678
17679        if (highestVersion != null) {
17680            return highestVersion.apk;
17681        }
17682
17683        return packageName;
17684    }
17685
17686    boolean isCallerVerifier(int callingUid) {
17687        final int callingUserId = UserHandle.getUserId(callingUid);
17688        return mRequiredVerifierPackage != null &&
17689                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17690    }
17691
17692    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17693        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17694              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17695            return true;
17696        }
17697        final int callingUserId = UserHandle.getUserId(callingUid);
17698        // If the caller installed the pkgName, then allow it to silently uninstall.
17699        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17700            return true;
17701        }
17702
17703        // Allow package verifier to silently uninstall.
17704        if (mRequiredVerifierPackage != null &&
17705                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17706            return true;
17707        }
17708
17709        // Allow package uninstaller to silently uninstall.
17710        if (mRequiredUninstallerPackage != null &&
17711                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17712            return true;
17713        }
17714
17715        // Allow storage manager to silently uninstall.
17716        if (mStorageManagerPackage != null &&
17717                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17718            return true;
17719        }
17720
17721        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17722        // uninstall for device owner provisioning.
17723        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17724                == PERMISSION_GRANTED) {
17725            return true;
17726        }
17727
17728        return false;
17729    }
17730
17731    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17732        int[] result = EMPTY_INT_ARRAY;
17733        for (int userId : userIds) {
17734            if (getBlockUninstallForUser(packageName, userId)) {
17735                result = ArrayUtils.appendInt(result, userId);
17736            }
17737        }
17738        return result;
17739    }
17740
17741    @Override
17742    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17743        final int callingUid = Binder.getCallingUid();
17744        if (getInstantAppPackageName(callingUid) != null
17745                && !isCallerSameApp(packageName, callingUid)) {
17746            return false;
17747        }
17748        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17749    }
17750
17751    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17752        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17753                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17754        try {
17755            if (dpm != null) {
17756                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17757                        /* callingUserOnly =*/ false);
17758                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17759                        : deviceOwnerComponentName.getPackageName();
17760                // Does the package contains the device owner?
17761                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17762                // this check is probably not needed, since DO should be registered as a device
17763                // admin on some user too. (Original bug for this: b/17657954)
17764                if (packageName.equals(deviceOwnerPackageName)) {
17765                    return true;
17766                }
17767                // Does it contain a device admin for any user?
17768                int[] users;
17769                if (userId == UserHandle.USER_ALL) {
17770                    users = sUserManager.getUserIds();
17771                } else {
17772                    users = new int[]{userId};
17773                }
17774                for (int i = 0; i < users.length; ++i) {
17775                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17776                        return true;
17777                    }
17778                }
17779            }
17780        } catch (RemoteException e) {
17781        }
17782        return false;
17783    }
17784
17785    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17786        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17787    }
17788
17789    /**
17790     *  This method is an internal method that could be get invoked either
17791     *  to delete an installed package or to clean up a failed installation.
17792     *  After deleting an installed package, a broadcast is sent to notify any
17793     *  listeners that the package has been removed. For cleaning up a failed
17794     *  installation, the broadcast is not necessary since the package's
17795     *  installation wouldn't have sent the initial broadcast either
17796     *  The key steps in deleting a package are
17797     *  deleting the package information in internal structures like mPackages,
17798     *  deleting the packages base directories through installd
17799     *  updating mSettings to reflect current status
17800     *  persisting settings for later use
17801     *  sending a broadcast if necessary
17802     */
17803    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17804        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17805        final boolean res;
17806
17807        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17808                ? UserHandle.USER_ALL : userId;
17809
17810        if (isPackageDeviceAdmin(packageName, removeUser)) {
17811            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17812            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17813        }
17814
17815        PackageSetting uninstalledPs = null;
17816        PackageParser.Package pkg = null;
17817
17818        // for the uninstall-updates case and restricted profiles, remember the per-
17819        // user handle installed state
17820        int[] allUsers;
17821        synchronized (mPackages) {
17822            uninstalledPs = mSettings.mPackages.get(packageName);
17823            if (uninstalledPs == null) {
17824                Slog.w(TAG, "Not removing non-existent package " + packageName);
17825                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17826            }
17827
17828            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17829                    && uninstalledPs.versionCode != versionCode) {
17830                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17831                        + uninstalledPs.versionCode + " != " + versionCode);
17832                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17833            }
17834
17835            // Static shared libs can be declared by any package, so let us not
17836            // allow removing a package if it provides a lib others depend on.
17837            pkg = mPackages.get(packageName);
17838
17839            allUsers = sUserManager.getUserIds();
17840
17841            if (pkg != null && pkg.staticSharedLibName != null) {
17842                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17843                        pkg.staticSharedLibVersion);
17844                if (libEntry != null) {
17845                    for (int currUserId : allUsers) {
17846                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17847                            continue;
17848                        }
17849                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17850                                libEntry.info, 0, currUserId);
17851                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17852                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17853                                    + " hosting lib " + libEntry.info.getName() + " version "
17854                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17855                                    + " for user " + currUserId);
17856                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17857                        }
17858                    }
17859                }
17860            }
17861
17862            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17863        }
17864
17865        final int freezeUser;
17866        if (isUpdatedSystemApp(uninstalledPs)
17867                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17868            // We're downgrading a system app, which will apply to all users, so
17869            // freeze them all during the downgrade
17870            freezeUser = UserHandle.USER_ALL;
17871        } else {
17872            freezeUser = removeUser;
17873        }
17874
17875        synchronized (mInstallLock) {
17876            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17877            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17878                    deleteFlags, "deletePackageX")) {
17879                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17880                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17881            }
17882            synchronized (mPackages) {
17883                if (res) {
17884                    if (pkg != null) {
17885                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17886                    }
17887                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17888                    updateInstantAppInstallerLocked(packageName);
17889                }
17890            }
17891        }
17892
17893        if (res) {
17894            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17895            info.sendPackageRemovedBroadcasts(killApp);
17896            info.sendSystemPackageUpdatedBroadcasts();
17897            info.sendSystemPackageAppearedBroadcasts();
17898        }
17899        // Force a gc here.
17900        Runtime.getRuntime().gc();
17901        // Delete the resources here after sending the broadcast to let
17902        // other processes clean up before deleting resources.
17903        if (info.args != null) {
17904            synchronized (mInstallLock) {
17905                info.args.doPostDeleteLI(true);
17906            }
17907        }
17908
17909        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17910    }
17911
17912    static class PackageRemovedInfo {
17913        final PackageSender packageSender;
17914        String removedPackage;
17915        String installerPackageName;
17916        int uid = -1;
17917        int removedAppId = -1;
17918        int[] origUsers;
17919        int[] removedUsers = null;
17920        int[] broadcastUsers = null;
17921        int[] instantUserIds = null;
17922        SparseArray<Integer> installReasons;
17923        boolean isRemovedPackageSystemUpdate = false;
17924        boolean isUpdate;
17925        boolean dataRemoved;
17926        boolean removedForAllUsers;
17927        boolean isStaticSharedLib;
17928        // Clean up resources deleted packages.
17929        InstallArgs args = null;
17930        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17931        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17932
17933        PackageRemovedInfo(PackageSender packageSender) {
17934            this.packageSender = packageSender;
17935        }
17936
17937        void sendPackageRemovedBroadcasts(boolean killApp) {
17938            sendPackageRemovedBroadcastInternal(killApp);
17939            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17940            for (int i = 0; i < childCount; i++) {
17941                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17942                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17943            }
17944        }
17945
17946        void sendSystemPackageUpdatedBroadcasts() {
17947            if (isRemovedPackageSystemUpdate) {
17948                sendSystemPackageUpdatedBroadcastsInternal();
17949                final int childCount = (removedChildPackages != null)
17950                        ? removedChildPackages.size() : 0;
17951                for (int i = 0; i < childCount; i++) {
17952                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17953                    if (childInfo.isRemovedPackageSystemUpdate) {
17954                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17955                    }
17956                }
17957            }
17958        }
17959
17960        void sendSystemPackageAppearedBroadcasts() {
17961            final int packageCount = (appearedChildPackages != null)
17962                    ? appearedChildPackages.size() : 0;
17963            for (int i = 0; i < packageCount; i++) {
17964                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17965                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17966                    true /*sendBootCompleted*/, false /*startReceiver*/,
17967                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
17968            }
17969        }
17970
17971        private void sendSystemPackageUpdatedBroadcastsInternal() {
17972            Bundle extras = new Bundle(2);
17973            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17974            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17975            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17976                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17977            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17978                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17979            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17980                null, null, 0, removedPackage, null, null, null);
17981            if (installerPackageName != null) {
17982                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17983                        removedPackage, extras, 0 /*flags*/,
17984                        installerPackageName, null, null, null);
17985                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17986                        removedPackage, extras, 0 /*flags*/,
17987                        installerPackageName, null, null, null);
17988            }
17989        }
17990
17991        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17992            // Don't send static shared library removal broadcasts as these
17993            // libs are visible only the the apps that depend on them an one
17994            // cannot remove the library if it has a dependency.
17995            if (isStaticSharedLib) {
17996                return;
17997            }
17998            Bundle extras = new Bundle(2);
17999            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18000            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18001            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18002            if (isUpdate || isRemovedPackageSystemUpdate) {
18003                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18004            }
18005            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18006            if (removedPackage != null) {
18007                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18008                    removedPackage, extras, 0, null /*targetPackage*/, null,
18009                    broadcastUsers, instantUserIds);
18010                if (installerPackageName != null) {
18011                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18012                            removedPackage, extras, 0 /*flags*/,
18013                            installerPackageName, null, broadcastUsers, instantUserIds);
18014                }
18015                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18016                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18017                        removedPackage, extras,
18018                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18019                        null, null, broadcastUsers, instantUserIds);
18020                    packageSender.notifyPackageRemoved(removedPackage);
18021                }
18022            }
18023            if (removedAppId >= 0) {
18024                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18025                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18026                    null, null, broadcastUsers, instantUserIds);
18027            }
18028        }
18029
18030        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18031            removedUsers = userIds;
18032            if (removedUsers == null) {
18033                broadcastUsers = null;
18034                return;
18035            }
18036
18037            broadcastUsers = EMPTY_INT_ARRAY;
18038            instantUserIds = EMPTY_INT_ARRAY;
18039            for (int i = userIds.length - 1; i >= 0; --i) {
18040                final int userId = userIds[i];
18041                if (deletedPackageSetting.getInstantApp(userId)) {
18042                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18043                } else {
18044                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18045                }
18046            }
18047        }
18048    }
18049
18050    /*
18051     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18052     * flag is not set, the data directory is removed as well.
18053     * make sure this flag is set for partially installed apps. If not its meaningless to
18054     * delete a partially installed application.
18055     */
18056    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18057            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18058        String packageName = ps.name;
18059        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18060        // Retrieve object to delete permissions for shared user later on
18061        final PackageParser.Package deletedPkg;
18062        final PackageSetting deletedPs;
18063        // reader
18064        synchronized (mPackages) {
18065            deletedPkg = mPackages.get(packageName);
18066            deletedPs = mSettings.mPackages.get(packageName);
18067            if (outInfo != null) {
18068                outInfo.removedPackage = packageName;
18069                outInfo.installerPackageName = ps.installerPackageName;
18070                outInfo.isStaticSharedLib = deletedPkg != null
18071                        && deletedPkg.staticSharedLibName != null;
18072                outInfo.populateUsers(deletedPs == null ? null
18073                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18074            }
18075        }
18076
18077        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18078
18079        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18080            final PackageParser.Package resolvedPkg;
18081            if (deletedPkg != null) {
18082                resolvedPkg = deletedPkg;
18083            } else {
18084                // We don't have a parsed package when it lives on an ejected
18085                // adopted storage device, so fake something together
18086                resolvedPkg = new PackageParser.Package(ps.name);
18087                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18088            }
18089            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18090                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18091            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18092            if (outInfo != null) {
18093                outInfo.dataRemoved = true;
18094            }
18095            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18096        }
18097
18098        int removedAppId = -1;
18099
18100        // writer
18101        synchronized (mPackages) {
18102            boolean installedStateChanged = false;
18103            if (deletedPs != null) {
18104                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18105                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18106                    clearDefaultBrowserIfNeeded(packageName);
18107                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18108                    removedAppId = mSettings.removePackageLPw(packageName);
18109                    if (outInfo != null) {
18110                        outInfo.removedAppId = removedAppId;
18111                    }
18112                    mPermissionManager.updatePermissions(
18113                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18114                    if (deletedPs.sharedUser != null) {
18115                        // Remove permissions associated with package. Since runtime
18116                        // permissions are per user we have to kill the removed package
18117                        // or packages running under the shared user of the removed
18118                        // package if revoking the permissions requested only by the removed
18119                        // package is successful and this causes a change in gids.
18120                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18121                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18122                                    userId);
18123                            if (userIdToKill == UserHandle.USER_ALL
18124                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18125                                // If gids changed for this user, kill all affected packages.
18126                                mHandler.post(new Runnable() {
18127                                    @Override
18128                                    public void run() {
18129                                        // This has to happen with no lock held.
18130                                        killApplication(deletedPs.name, deletedPs.appId,
18131                                                KILL_APP_REASON_GIDS_CHANGED);
18132                                    }
18133                                });
18134                                break;
18135                            }
18136                        }
18137                    }
18138                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18139                }
18140                // make sure to preserve per-user disabled state if this removal was just
18141                // a downgrade of a system app to the factory package
18142                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18143                    if (DEBUG_REMOVE) {
18144                        Slog.d(TAG, "Propagating install state across downgrade");
18145                    }
18146                    for (int userId : allUserHandles) {
18147                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18148                        if (DEBUG_REMOVE) {
18149                            Slog.d(TAG, "    user " + userId + " => " + installed);
18150                        }
18151                        if (installed != ps.getInstalled(userId)) {
18152                            installedStateChanged = true;
18153                        }
18154                        ps.setInstalled(installed, userId);
18155                    }
18156                }
18157            }
18158            // can downgrade to reader
18159            if (writeSettings) {
18160                // Save settings now
18161                mSettings.writeLPr();
18162            }
18163            if (installedStateChanged) {
18164                mSettings.writeKernelMappingLPr(ps);
18165            }
18166        }
18167        if (removedAppId != -1) {
18168            // A user ID was deleted here. Go through all users and remove it
18169            // from KeyStore.
18170            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18171        }
18172    }
18173
18174    static boolean locationIsPrivileged(String path) {
18175        try {
18176            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18177            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18178            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18179            return path.startsWith(privilegedAppDir.getCanonicalPath())
18180                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18181                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18182        } catch (IOException e) {
18183            Slog.e(TAG, "Unable to access code path " + path);
18184        }
18185        return false;
18186    }
18187
18188    static boolean locationIsOem(String path) {
18189        try {
18190            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18191        } catch (IOException e) {
18192            Slog.e(TAG, "Unable to access code path " + path);
18193        }
18194        return false;
18195    }
18196
18197    static boolean locationIsVendor(String path) {
18198        try {
18199            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
18200        } catch (IOException e) {
18201            Slog.e(TAG, "Unable to access code path " + path);
18202        }
18203        return false;
18204    }
18205
18206    static boolean locationIsProduct(String path) {
18207        try {
18208            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18209        } catch (IOException e) {
18210            Slog.e(TAG, "Unable to access code path " + path);
18211        }
18212        return false;
18213    }
18214
18215    /*
18216     * Tries to delete system package.
18217     */
18218    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18219            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18220            boolean writeSettings) {
18221        if (deletedPs.parentPackageName != null) {
18222            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18223            return false;
18224        }
18225
18226        final boolean applyUserRestrictions
18227                = (allUserHandles != null) && (outInfo.origUsers != null);
18228        final PackageSetting disabledPs;
18229        // Confirm if the system package has been updated
18230        // An updated system app can be deleted. This will also have to restore
18231        // the system pkg from system partition
18232        // reader
18233        synchronized (mPackages) {
18234            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18235        }
18236
18237        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18238                + " disabledPs=" + disabledPs);
18239
18240        if (disabledPs == null) {
18241            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18242            return false;
18243        } else if (DEBUG_REMOVE) {
18244            Slog.d(TAG, "Deleting system pkg from data partition");
18245        }
18246
18247        if (DEBUG_REMOVE) {
18248            if (applyUserRestrictions) {
18249                Slog.d(TAG, "Remembering install states:");
18250                for (int userId : allUserHandles) {
18251                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18252                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18253                }
18254            }
18255        }
18256
18257        // Delete the updated package
18258        outInfo.isRemovedPackageSystemUpdate = true;
18259        if (outInfo.removedChildPackages != null) {
18260            final int childCount = (deletedPs.childPackageNames != null)
18261                    ? deletedPs.childPackageNames.size() : 0;
18262            for (int i = 0; i < childCount; i++) {
18263                String childPackageName = deletedPs.childPackageNames.get(i);
18264                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18265                        .contains(childPackageName)) {
18266                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18267                            childPackageName);
18268                    if (childInfo != null) {
18269                        childInfo.isRemovedPackageSystemUpdate = true;
18270                    }
18271                }
18272            }
18273        }
18274
18275        if (disabledPs.versionCode < deletedPs.versionCode) {
18276            // Delete data for downgrades
18277            flags &= ~PackageManager.DELETE_KEEP_DATA;
18278        } else {
18279            // Preserve data by setting flag
18280            flags |= PackageManager.DELETE_KEEP_DATA;
18281        }
18282
18283        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18284                outInfo, writeSettings, disabledPs.pkg);
18285        if (!ret) {
18286            return false;
18287        }
18288
18289        // writer
18290        synchronized (mPackages) {
18291            // NOTE: The system package always needs to be enabled; even if it's for
18292            // a compressed stub. If we don't, installing the system package fails
18293            // during scan [scanning checks the disabled packages]. We will reverse
18294            // this later, after we've "installed" the stub.
18295            // Reinstate the old system package
18296            enableSystemPackageLPw(disabledPs.pkg);
18297            // Remove any native libraries from the upgraded package.
18298            removeNativeBinariesLI(deletedPs);
18299        }
18300
18301        // Install the system package
18302        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18303        try {
18304            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18305                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18306        } catch (PackageManagerException e) {
18307            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18308                    + e.getMessage());
18309            return false;
18310        } finally {
18311            if (disabledPs.pkg.isStub) {
18312                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18313            }
18314        }
18315        return true;
18316    }
18317
18318    /**
18319     * Installs a package that's already on the system partition.
18320     */
18321    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18322            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18323            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18324                    throws PackageManagerException {
18325        @ParseFlags int parseFlags =
18326                mDefParseFlags
18327                | PackageParser.PARSE_MUST_BE_APK
18328                | PackageParser.PARSE_IS_SYSTEM_DIR;
18329        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18330        if (isPrivileged || locationIsPrivileged(codePathString)) {
18331            scanFlags |= SCAN_AS_PRIVILEGED;
18332        }
18333        if (locationIsOem(codePathString)) {
18334            scanFlags |= SCAN_AS_OEM;
18335        }
18336        if (locationIsVendor(codePathString)) {
18337            scanFlags |= SCAN_AS_VENDOR;
18338        }
18339        if (locationIsProduct(codePathString)) {
18340            scanFlags |= SCAN_AS_PRODUCT;
18341        }
18342
18343        final File codePath = new File(codePathString);
18344        final PackageParser.Package pkg =
18345                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18346
18347        try {
18348            // update shared libraries for the newly re-installed system package
18349            updateSharedLibrariesLPr(pkg, null);
18350        } catch (PackageManagerException e) {
18351            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18352        }
18353
18354        prepareAppDataAfterInstallLIF(pkg);
18355
18356        // writer
18357        synchronized (mPackages) {
18358            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18359
18360            // Propagate the permissions state as we do not want to drop on the floor
18361            // runtime permissions. The update permissions method below will take
18362            // care of removing obsolete permissions and grant install permissions.
18363            if (origPermissionState != null) {
18364                ps.getPermissionsState().copyFrom(origPermissionState);
18365            }
18366            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18367                    mPermissionCallback);
18368
18369            final boolean applyUserRestrictions
18370                    = (allUserHandles != null) && (origUserHandles != null);
18371            if (applyUserRestrictions) {
18372                boolean installedStateChanged = false;
18373                if (DEBUG_REMOVE) {
18374                    Slog.d(TAG, "Propagating install state across reinstall");
18375                }
18376                for (int userId : allUserHandles) {
18377                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18378                    if (DEBUG_REMOVE) {
18379                        Slog.d(TAG, "    user " + userId + " => " + installed);
18380                    }
18381                    if (installed != ps.getInstalled(userId)) {
18382                        installedStateChanged = true;
18383                    }
18384                    ps.setInstalled(installed, userId);
18385
18386                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18387                }
18388                // Regardless of writeSettings we need to ensure that this restriction
18389                // state propagation is persisted
18390                mSettings.writeAllUsersPackageRestrictionsLPr();
18391                if (installedStateChanged) {
18392                    mSettings.writeKernelMappingLPr(ps);
18393                }
18394            }
18395            // can downgrade to reader here
18396            if (writeSettings) {
18397                mSettings.writeLPr();
18398            }
18399        }
18400        return pkg;
18401    }
18402
18403    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18404            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18405            PackageRemovedInfo outInfo, boolean writeSettings,
18406            PackageParser.Package replacingPackage) {
18407        synchronized (mPackages) {
18408            if (outInfo != null) {
18409                outInfo.uid = ps.appId;
18410            }
18411
18412            if (outInfo != null && outInfo.removedChildPackages != null) {
18413                final int childCount = (ps.childPackageNames != null)
18414                        ? ps.childPackageNames.size() : 0;
18415                for (int i = 0; i < childCount; i++) {
18416                    String childPackageName = ps.childPackageNames.get(i);
18417                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18418                    if (childPs == null) {
18419                        return false;
18420                    }
18421                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18422                            childPackageName);
18423                    if (childInfo != null) {
18424                        childInfo.uid = childPs.appId;
18425                    }
18426                }
18427            }
18428        }
18429
18430        // Delete package data from internal structures and also remove data if flag is set
18431        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18432
18433        // Delete the child packages data
18434        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18435        for (int i = 0; i < childCount; i++) {
18436            PackageSetting childPs;
18437            synchronized (mPackages) {
18438                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18439            }
18440            if (childPs != null) {
18441                PackageRemovedInfo childOutInfo = (outInfo != null
18442                        && outInfo.removedChildPackages != null)
18443                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18444                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18445                        && (replacingPackage != null
18446                        && !replacingPackage.hasChildPackage(childPs.name))
18447                        ? flags & ~DELETE_KEEP_DATA : flags;
18448                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18449                        deleteFlags, writeSettings);
18450            }
18451        }
18452
18453        // Delete application code and resources only for parent packages
18454        if (ps.parentPackageName == null) {
18455            if (deleteCodeAndResources && (outInfo != null)) {
18456                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18457                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18458                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18459            }
18460        }
18461
18462        return true;
18463    }
18464
18465    @Override
18466    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18467            int userId) {
18468        mContext.enforceCallingOrSelfPermission(
18469                android.Manifest.permission.DELETE_PACKAGES, null);
18470        synchronized (mPackages) {
18471            // Cannot block uninstall of static shared libs as they are
18472            // considered a part of the using app (emulating static linking).
18473            // Also static libs are installed always on internal storage.
18474            PackageParser.Package pkg = mPackages.get(packageName);
18475            if (pkg != null && pkg.staticSharedLibName != null) {
18476                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18477                        + " providing static shared library: " + pkg.staticSharedLibName);
18478                return false;
18479            }
18480            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18481            mSettings.writePackageRestrictionsLPr(userId);
18482        }
18483        return true;
18484    }
18485
18486    @Override
18487    public boolean getBlockUninstallForUser(String packageName, int userId) {
18488        synchronized (mPackages) {
18489            final PackageSetting ps = mSettings.mPackages.get(packageName);
18490            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18491                return false;
18492            }
18493            return mSettings.getBlockUninstallLPr(userId, packageName);
18494        }
18495    }
18496
18497    @Override
18498    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18499        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18500        synchronized (mPackages) {
18501            PackageSetting ps = mSettings.mPackages.get(packageName);
18502            if (ps == null) {
18503                Log.w(TAG, "Package doesn't exist: " + packageName);
18504                return false;
18505            }
18506            if (systemUserApp) {
18507                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18508            } else {
18509                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18510            }
18511            mSettings.writeLPr();
18512        }
18513        return true;
18514    }
18515
18516    /*
18517     * This method handles package deletion in general
18518     */
18519    private boolean deletePackageLIF(String packageName, UserHandle user,
18520            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18521            PackageRemovedInfo outInfo, boolean writeSettings,
18522            PackageParser.Package replacingPackage) {
18523        if (packageName == null) {
18524            Slog.w(TAG, "Attempt to delete null packageName.");
18525            return false;
18526        }
18527
18528        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18529
18530        PackageSetting ps;
18531        synchronized (mPackages) {
18532            ps = mSettings.mPackages.get(packageName);
18533            if (ps == null) {
18534                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18535                return false;
18536            }
18537
18538            if (ps.parentPackageName != null && (!isSystemApp(ps)
18539                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18540                if (DEBUG_REMOVE) {
18541                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18542                            + ((user == null) ? UserHandle.USER_ALL : user));
18543                }
18544                final int removedUserId = (user != null) ? user.getIdentifier()
18545                        : UserHandle.USER_ALL;
18546                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18547                    return false;
18548                }
18549                markPackageUninstalledForUserLPw(ps, user);
18550                scheduleWritePackageRestrictionsLocked(user);
18551                return true;
18552            }
18553        }
18554
18555        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18556                && user.getIdentifier() != UserHandle.USER_ALL)) {
18557            // The caller is asking that the package only be deleted for a single
18558            // user.  To do this, we just mark its uninstalled state and delete
18559            // its data. If this is a system app, we only allow this to happen if
18560            // they have set the special DELETE_SYSTEM_APP which requests different
18561            // semantics than normal for uninstalling system apps.
18562            markPackageUninstalledForUserLPw(ps, user);
18563
18564            if (!isSystemApp(ps)) {
18565                // Do not uninstall the APK if an app should be cached
18566                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18567                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18568                    // Other user still have this package installed, so all
18569                    // we need to do is clear this user's data and save that
18570                    // it is uninstalled.
18571                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18572                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18573                        return false;
18574                    }
18575                    scheduleWritePackageRestrictionsLocked(user);
18576                    return true;
18577                } else {
18578                    // We need to set it back to 'installed' so the uninstall
18579                    // broadcasts will be sent correctly.
18580                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18581                    ps.setInstalled(true, user.getIdentifier());
18582                    mSettings.writeKernelMappingLPr(ps);
18583                }
18584            } else {
18585                // This is a system app, so we assume that the
18586                // other users still have this package installed, so all
18587                // we need to do is clear this user's data and save that
18588                // it is uninstalled.
18589                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18590                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18591                    return false;
18592                }
18593                scheduleWritePackageRestrictionsLocked(user);
18594                return true;
18595            }
18596        }
18597
18598        // If we are deleting a composite package for all users, keep track
18599        // of result for each child.
18600        if (ps.childPackageNames != null && outInfo != null) {
18601            synchronized (mPackages) {
18602                final int childCount = ps.childPackageNames.size();
18603                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18604                for (int i = 0; i < childCount; i++) {
18605                    String childPackageName = ps.childPackageNames.get(i);
18606                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18607                    childInfo.removedPackage = childPackageName;
18608                    childInfo.installerPackageName = ps.installerPackageName;
18609                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18610                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18611                    if (childPs != null) {
18612                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18613                    }
18614                }
18615            }
18616        }
18617
18618        boolean ret = false;
18619        if (isSystemApp(ps)) {
18620            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18621            // When an updated system application is deleted we delete the existing resources
18622            // as well and fall back to existing code in system partition
18623            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18624        } else {
18625            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18626            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18627                    outInfo, writeSettings, replacingPackage);
18628        }
18629
18630        // Take a note whether we deleted the package for all users
18631        if (outInfo != null) {
18632            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18633            if (outInfo.removedChildPackages != null) {
18634                synchronized (mPackages) {
18635                    final int childCount = outInfo.removedChildPackages.size();
18636                    for (int i = 0; i < childCount; i++) {
18637                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18638                        if (childInfo != null) {
18639                            childInfo.removedForAllUsers = mPackages.get(
18640                                    childInfo.removedPackage) == null;
18641                        }
18642                    }
18643                }
18644            }
18645            // If we uninstalled an update to a system app there may be some
18646            // child packages that appeared as they are declared in the system
18647            // app but were not declared in the update.
18648            if (isSystemApp(ps)) {
18649                synchronized (mPackages) {
18650                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18651                    final int childCount = (updatedPs.childPackageNames != null)
18652                            ? updatedPs.childPackageNames.size() : 0;
18653                    for (int i = 0; i < childCount; i++) {
18654                        String childPackageName = updatedPs.childPackageNames.get(i);
18655                        if (outInfo.removedChildPackages == null
18656                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18657                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18658                            if (childPs == null) {
18659                                continue;
18660                            }
18661                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18662                            installRes.name = childPackageName;
18663                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18664                            installRes.pkg = mPackages.get(childPackageName);
18665                            installRes.uid = childPs.pkg.applicationInfo.uid;
18666                            if (outInfo.appearedChildPackages == null) {
18667                                outInfo.appearedChildPackages = new ArrayMap<>();
18668                            }
18669                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18670                        }
18671                    }
18672                }
18673            }
18674        }
18675
18676        return ret;
18677    }
18678
18679    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18680        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18681                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18682        for (int nextUserId : userIds) {
18683            if (DEBUG_REMOVE) {
18684                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18685            }
18686            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18687                    false /*installed*/,
18688                    true /*stopped*/,
18689                    true /*notLaunched*/,
18690                    false /*hidden*/,
18691                    false /*suspended*/,
18692                    false /*instantApp*/,
18693                    false /*virtualPreload*/,
18694                    null /*lastDisableAppCaller*/,
18695                    null /*enabledComponents*/,
18696                    null /*disabledComponents*/,
18697                    ps.readUserState(nextUserId).domainVerificationStatus,
18698                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18699                    null /*harmfulAppWarning*/);
18700        }
18701        mSettings.writeKernelMappingLPr(ps);
18702    }
18703
18704    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18705            PackageRemovedInfo outInfo) {
18706        final PackageParser.Package pkg;
18707        synchronized (mPackages) {
18708            pkg = mPackages.get(ps.name);
18709        }
18710
18711        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18712                : new int[] {userId};
18713        for (int nextUserId : userIds) {
18714            if (DEBUG_REMOVE) {
18715                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18716                        + nextUserId);
18717            }
18718
18719            destroyAppDataLIF(pkg, userId,
18720                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18721            destroyAppProfilesLIF(pkg, userId);
18722            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18723            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18724            schedulePackageCleaning(ps.name, nextUserId, false);
18725            synchronized (mPackages) {
18726                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18727                    scheduleWritePackageRestrictionsLocked(nextUserId);
18728                }
18729                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18730            }
18731        }
18732
18733        if (outInfo != null) {
18734            outInfo.removedPackage = ps.name;
18735            outInfo.installerPackageName = ps.installerPackageName;
18736            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18737            outInfo.removedAppId = ps.appId;
18738            outInfo.removedUsers = userIds;
18739            outInfo.broadcastUsers = userIds;
18740        }
18741
18742        return true;
18743    }
18744
18745    private final class ClearStorageConnection implements ServiceConnection {
18746        IMediaContainerService mContainerService;
18747
18748        @Override
18749        public void onServiceConnected(ComponentName name, IBinder service) {
18750            synchronized (this) {
18751                mContainerService = IMediaContainerService.Stub
18752                        .asInterface(Binder.allowBlocking(service));
18753                notifyAll();
18754            }
18755        }
18756
18757        @Override
18758        public void onServiceDisconnected(ComponentName name) {
18759        }
18760    }
18761
18762    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18763        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18764
18765        final boolean mounted;
18766        if (Environment.isExternalStorageEmulated()) {
18767            mounted = true;
18768        } else {
18769            final String status = Environment.getExternalStorageState();
18770
18771            mounted = status.equals(Environment.MEDIA_MOUNTED)
18772                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18773        }
18774
18775        if (!mounted) {
18776            return;
18777        }
18778
18779        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18780        int[] users;
18781        if (userId == UserHandle.USER_ALL) {
18782            users = sUserManager.getUserIds();
18783        } else {
18784            users = new int[] { userId };
18785        }
18786        final ClearStorageConnection conn = new ClearStorageConnection();
18787        if (mContext.bindServiceAsUser(
18788                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18789            try {
18790                for (int curUser : users) {
18791                    long timeout = SystemClock.uptimeMillis() + 5000;
18792                    synchronized (conn) {
18793                        long now;
18794                        while (conn.mContainerService == null &&
18795                                (now = SystemClock.uptimeMillis()) < timeout) {
18796                            try {
18797                                conn.wait(timeout - now);
18798                            } catch (InterruptedException e) {
18799                            }
18800                        }
18801                    }
18802                    if (conn.mContainerService == null) {
18803                        return;
18804                    }
18805
18806                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18807                    clearDirectory(conn.mContainerService,
18808                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18809                    if (allData) {
18810                        clearDirectory(conn.mContainerService,
18811                                userEnv.buildExternalStorageAppDataDirs(packageName));
18812                        clearDirectory(conn.mContainerService,
18813                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18814                    }
18815                }
18816            } finally {
18817                mContext.unbindService(conn);
18818            }
18819        }
18820    }
18821
18822    @Override
18823    public void clearApplicationProfileData(String packageName) {
18824        enforceSystemOrRoot("Only the system can clear all profile data");
18825
18826        final PackageParser.Package pkg;
18827        synchronized (mPackages) {
18828            pkg = mPackages.get(packageName);
18829        }
18830
18831        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18832            synchronized (mInstallLock) {
18833                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18834            }
18835        }
18836    }
18837
18838    @Override
18839    public void clearApplicationUserData(final String packageName,
18840            final IPackageDataObserver observer, final int userId) {
18841        mContext.enforceCallingOrSelfPermission(
18842                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18843
18844        final int callingUid = Binder.getCallingUid();
18845        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18846                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18847
18848        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18849        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18850        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18851            throw new SecurityException("Cannot clear data for a protected package: "
18852                    + packageName);
18853        }
18854        // Queue up an async operation since the package deletion may take a little while.
18855        mHandler.post(new Runnable() {
18856            public void run() {
18857                mHandler.removeCallbacks(this);
18858                final boolean succeeded;
18859                if (!filterApp) {
18860                    try (PackageFreezer freezer = freezePackage(packageName,
18861                            "clearApplicationUserData")) {
18862                        synchronized (mInstallLock) {
18863                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18864                        }
18865                        clearExternalStorageDataSync(packageName, userId, true);
18866                        synchronized (mPackages) {
18867                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18868                                    packageName, userId);
18869                        }
18870                    }
18871                    if (succeeded) {
18872                        // invoke DeviceStorageMonitor's update method to clear any notifications
18873                        DeviceStorageMonitorInternal dsm = LocalServices
18874                                .getService(DeviceStorageMonitorInternal.class);
18875                        if (dsm != null) {
18876                            dsm.checkMemory();
18877                        }
18878                    }
18879                } else {
18880                    succeeded = false;
18881                }
18882                if (observer != null) {
18883                    try {
18884                        observer.onRemoveCompleted(packageName, succeeded);
18885                    } catch (RemoteException e) {
18886                        Log.i(TAG, "Observer no longer exists.");
18887                    }
18888                } //end if observer
18889            } //end run
18890        });
18891    }
18892
18893    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18894        if (packageName == null) {
18895            Slog.w(TAG, "Attempt to delete null packageName.");
18896            return false;
18897        }
18898
18899        // Try finding details about the requested package
18900        PackageParser.Package pkg;
18901        synchronized (mPackages) {
18902            pkg = mPackages.get(packageName);
18903            if (pkg == null) {
18904                final PackageSetting ps = mSettings.mPackages.get(packageName);
18905                if (ps != null) {
18906                    pkg = ps.pkg;
18907                }
18908            }
18909
18910            if (pkg == null) {
18911                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18912                return false;
18913            }
18914
18915            PackageSetting ps = (PackageSetting) pkg.mExtras;
18916            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18917        }
18918
18919        clearAppDataLIF(pkg, userId,
18920                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18921
18922        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18923        removeKeystoreDataIfNeeded(userId, appId);
18924
18925        UserManagerInternal umInternal = getUserManagerInternal();
18926        final int flags;
18927        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18928            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18929        } else if (umInternal.isUserRunning(userId)) {
18930            flags = StorageManager.FLAG_STORAGE_DE;
18931        } else {
18932            flags = 0;
18933        }
18934        prepareAppDataContentsLIF(pkg, userId, flags);
18935
18936        return true;
18937    }
18938
18939    /**
18940     * Reverts user permission state changes (permissions and flags) in
18941     * all packages for a given user.
18942     *
18943     * @param userId The device user for which to do a reset.
18944     */
18945    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18946        final int packageCount = mPackages.size();
18947        for (int i = 0; i < packageCount; i++) {
18948            PackageParser.Package pkg = mPackages.valueAt(i);
18949            PackageSetting ps = (PackageSetting) pkg.mExtras;
18950            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18951        }
18952    }
18953
18954    private void resetNetworkPolicies(int userId) {
18955        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18956    }
18957
18958    /**
18959     * Reverts user permission state changes (permissions and flags).
18960     *
18961     * @param ps The package for which to reset.
18962     * @param userId The device user for which to do a reset.
18963     */
18964    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18965            final PackageSetting ps, final int userId) {
18966        if (ps.pkg == null) {
18967            return;
18968        }
18969
18970        // These are flags that can change base on user actions.
18971        final int userSettableMask = FLAG_PERMISSION_USER_SET
18972                | FLAG_PERMISSION_USER_FIXED
18973                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18974                | FLAG_PERMISSION_REVIEW_REQUIRED;
18975
18976        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18977                | FLAG_PERMISSION_POLICY_FIXED;
18978
18979        boolean writeInstallPermissions = false;
18980        boolean writeRuntimePermissions = false;
18981
18982        final int permissionCount = ps.pkg.requestedPermissions.size();
18983        for (int i = 0; i < permissionCount; i++) {
18984            final String permName = ps.pkg.requestedPermissions.get(i);
18985            final BasePermission bp =
18986                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18987            if (bp == null) {
18988                continue;
18989            }
18990
18991            // If shared user we just reset the state to which only this app contributed.
18992            if (ps.sharedUser != null) {
18993                boolean used = false;
18994                final int packageCount = ps.sharedUser.packages.size();
18995                for (int j = 0; j < packageCount; j++) {
18996                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18997                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18998                            && pkg.pkg.requestedPermissions.contains(permName)) {
18999                        used = true;
19000                        break;
19001                    }
19002                }
19003                if (used) {
19004                    continue;
19005                }
19006            }
19007
19008            final PermissionsState permissionsState = ps.getPermissionsState();
19009
19010            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19011
19012            // Always clear the user settable flags.
19013            final boolean hasInstallState =
19014                    permissionsState.getInstallPermissionState(permName) != null;
19015            // If permission review is enabled and this is a legacy app, mark the
19016            // permission as requiring a review as this is the initial state.
19017            int flags = 0;
19018            if (mSettings.mPermissions.mPermissionReviewRequired
19019                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19020                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19021            }
19022            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19023                if (hasInstallState) {
19024                    writeInstallPermissions = true;
19025                } else {
19026                    writeRuntimePermissions = true;
19027                }
19028            }
19029
19030            // Below is only runtime permission handling.
19031            if (!bp.isRuntime()) {
19032                continue;
19033            }
19034
19035            // Never clobber system or policy.
19036            if ((oldFlags & policyOrSystemFlags) != 0) {
19037                continue;
19038            }
19039
19040            // If this permission was granted by default, make sure it is.
19041            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19042                if (permissionsState.grantRuntimePermission(bp, userId)
19043                        != PERMISSION_OPERATION_FAILURE) {
19044                    writeRuntimePermissions = true;
19045                }
19046            // If permission review is enabled the permissions for a legacy apps
19047            // are represented as constantly granted runtime ones, so don't revoke.
19048            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19049                // Otherwise, reset the permission.
19050                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19051                switch (revokeResult) {
19052                    case PERMISSION_OPERATION_SUCCESS:
19053                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19054                        writeRuntimePermissions = true;
19055                        final int appId = ps.appId;
19056                        mHandler.post(new Runnable() {
19057                            @Override
19058                            public void run() {
19059                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19060                            }
19061                        });
19062                    } break;
19063                }
19064            }
19065        }
19066
19067        // Synchronously write as we are taking permissions away.
19068        if (writeRuntimePermissions) {
19069            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19070        }
19071
19072        // Synchronously write as we are taking permissions away.
19073        if (writeInstallPermissions) {
19074            mSettings.writeLPr();
19075        }
19076    }
19077
19078    /**
19079     * Remove entries from the keystore daemon. Will only remove it if the
19080     * {@code appId} is valid.
19081     */
19082    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19083        if (appId < 0) {
19084            return;
19085        }
19086
19087        final KeyStore keyStore = KeyStore.getInstance();
19088        if (keyStore != null) {
19089            if (userId == UserHandle.USER_ALL) {
19090                for (final int individual : sUserManager.getUserIds()) {
19091                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19092                }
19093            } else {
19094                keyStore.clearUid(UserHandle.getUid(userId, appId));
19095            }
19096        } else {
19097            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19098        }
19099    }
19100
19101    @Override
19102    public void deleteApplicationCacheFiles(final String packageName,
19103            final IPackageDataObserver observer) {
19104        final int userId = UserHandle.getCallingUserId();
19105        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19106    }
19107
19108    @Override
19109    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19110            final IPackageDataObserver observer) {
19111        final int callingUid = Binder.getCallingUid();
19112        mContext.enforceCallingOrSelfPermission(
19113                android.Manifest.permission.DELETE_CACHE_FILES, null);
19114        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19115                /* requireFullPermission= */ true, /* checkShell= */ false,
19116                "delete application cache files");
19117        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19118                android.Manifest.permission.ACCESS_INSTANT_APPS);
19119
19120        final PackageParser.Package pkg;
19121        synchronized (mPackages) {
19122            pkg = mPackages.get(packageName);
19123        }
19124
19125        // Queue up an async operation since the package deletion may take a little while.
19126        mHandler.post(new Runnable() {
19127            public void run() {
19128                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19129                boolean doClearData = true;
19130                if (ps != null) {
19131                    final boolean targetIsInstantApp =
19132                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19133                    doClearData = !targetIsInstantApp
19134                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19135                }
19136                if (doClearData) {
19137                    synchronized (mInstallLock) {
19138                        final int flags = StorageManager.FLAG_STORAGE_DE
19139                                | StorageManager.FLAG_STORAGE_CE;
19140                        // We're only clearing cache files, so we don't care if the
19141                        // app is unfrozen and still able to run
19142                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19143                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19144                    }
19145                    clearExternalStorageDataSync(packageName, userId, false);
19146                }
19147                if (observer != null) {
19148                    try {
19149                        observer.onRemoveCompleted(packageName, true);
19150                    } catch (RemoteException e) {
19151                        Log.i(TAG, "Observer no longer exists.");
19152                    }
19153                }
19154            }
19155        });
19156    }
19157
19158    @Override
19159    public void getPackageSizeInfo(final String packageName, int userHandle,
19160            final IPackageStatsObserver observer) {
19161        throw new UnsupportedOperationException(
19162                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19163    }
19164
19165    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19166        final PackageSetting ps;
19167        synchronized (mPackages) {
19168            ps = mSettings.mPackages.get(packageName);
19169            if (ps == null) {
19170                Slog.w(TAG, "Failed to find settings for " + packageName);
19171                return false;
19172            }
19173        }
19174
19175        final String[] packageNames = { packageName };
19176        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19177        final String[] codePaths = { ps.codePathString };
19178
19179        try {
19180            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19181                    ps.appId, ceDataInodes, codePaths, stats);
19182
19183            // For now, ignore code size of packages on system partition
19184            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19185                stats.codeSize = 0;
19186            }
19187
19188            // External clients expect these to be tracked separately
19189            stats.dataSize -= stats.cacheSize;
19190
19191        } catch (InstallerException e) {
19192            Slog.w(TAG, String.valueOf(e));
19193            return false;
19194        }
19195
19196        return true;
19197    }
19198
19199    private int getUidTargetSdkVersionLockedLPr(int uid) {
19200        Object obj = mSettings.getUserIdLPr(uid);
19201        if (obj instanceof SharedUserSetting) {
19202            final SharedUserSetting sus = (SharedUserSetting) obj;
19203            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19204            final Iterator<PackageSetting> it = sus.packages.iterator();
19205            while (it.hasNext()) {
19206                final PackageSetting ps = it.next();
19207                if (ps.pkg != null) {
19208                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19209                    if (v < vers) vers = v;
19210                }
19211            }
19212            return vers;
19213        } else if (obj instanceof PackageSetting) {
19214            final PackageSetting ps = (PackageSetting) obj;
19215            if (ps.pkg != null) {
19216                return ps.pkg.applicationInfo.targetSdkVersion;
19217            }
19218        }
19219        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19220    }
19221
19222    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19223        final PackageParser.Package p = mPackages.get(packageName);
19224        if (p != null) {
19225            return p.applicationInfo.targetSdkVersion;
19226        }
19227        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19228    }
19229
19230    @Override
19231    public void addPreferredActivity(IntentFilter filter, int match,
19232            ComponentName[] set, ComponentName activity, int userId) {
19233        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19234                "Adding preferred");
19235    }
19236
19237    private void addPreferredActivityInternal(IntentFilter filter, int match,
19238            ComponentName[] set, ComponentName activity, boolean always, int userId,
19239            String opname) {
19240        // writer
19241        int callingUid = Binder.getCallingUid();
19242        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19243                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19244        if (filter.countActions() == 0) {
19245            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19246            return;
19247        }
19248        synchronized (mPackages) {
19249            if (mContext.checkCallingOrSelfPermission(
19250                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19251                    != PackageManager.PERMISSION_GRANTED) {
19252                if (getUidTargetSdkVersionLockedLPr(callingUid)
19253                        < Build.VERSION_CODES.FROYO) {
19254                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19255                            + callingUid);
19256                    return;
19257                }
19258                mContext.enforceCallingOrSelfPermission(
19259                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19260            }
19261
19262            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19263            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19264                    + userId + ":");
19265            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19266            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19267            scheduleWritePackageRestrictionsLocked(userId);
19268            postPreferredActivityChangedBroadcast(userId);
19269        }
19270    }
19271
19272    private void postPreferredActivityChangedBroadcast(int userId) {
19273        mHandler.post(() -> {
19274            final IActivityManager am = ActivityManager.getService();
19275            if (am == null) {
19276                return;
19277            }
19278
19279            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19280            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19281            try {
19282                am.broadcastIntent(null, intent, null, null,
19283                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19284                        null, false, false, userId);
19285            } catch (RemoteException e) {
19286            }
19287        });
19288    }
19289
19290    @Override
19291    public void replacePreferredActivity(IntentFilter filter, int match,
19292            ComponentName[] set, ComponentName activity, int userId) {
19293        if (filter.countActions() != 1) {
19294            throw new IllegalArgumentException(
19295                    "replacePreferredActivity expects filter to have only 1 action.");
19296        }
19297        if (filter.countDataAuthorities() != 0
19298                || filter.countDataPaths() != 0
19299                || filter.countDataSchemes() > 1
19300                || filter.countDataTypes() != 0) {
19301            throw new IllegalArgumentException(
19302                    "replacePreferredActivity expects filter to have no data authorities, " +
19303                    "paths, or types; and at most one scheme.");
19304        }
19305
19306        final int callingUid = Binder.getCallingUid();
19307        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19308                true /* requireFullPermission */, false /* checkShell */,
19309                "replace preferred activity");
19310        synchronized (mPackages) {
19311            if (mContext.checkCallingOrSelfPermission(
19312                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19313                    != PackageManager.PERMISSION_GRANTED) {
19314                if (getUidTargetSdkVersionLockedLPr(callingUid)
19315                        < Build.VERSION_CODES.FROYO) {
19316                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19317                            + Binder.getCallingUid());
19318                    return;
19319                }
19320                mContext.enforceCallingOrSelfPermission(
19321                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19322            }
19323
19324            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19325            if (pir != null) {
19326                // Get all of the existing entries that exactly match this filter.
19327                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19328                if (existing != null && existing.size() == 1) {
19329                    PreferredActivity cur = existing.get(0);
19330                    if (DEBUG_PREFERRED) {
19331                        Slog.i(TAG, "Checking replace of preferred:");
19332                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19333                        if (!cur.mPref.mAlways) {
19334                            Slog.i(TAG, "  -- CUR; not mAlways!");
19335                        } else {
19336                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19337                            Slog.i(TAG, "  -- CUR: mSet="
19338                                    + Arrays.toString(cur.mPref.mSetComponents));
19339                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19340                            Slog.i(TAG, "  -- NEW: mMatch="
19341                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19342                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19343                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19344                        }
19345                    }
19346                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19347                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19348                            && cur.mPref.sameSet(set)) {
19349                        // Setting the preferred activity to what it happens to be already
19350                        if (DEBUG_PREFERRED) {
19351                            Slog.i(TAG, "Replacing with same preferred activity "
19352                                    + cur.mPref.mShortComponent + " for user "
19353                                    + userId + ":");
19354                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19355                        }
19356                        return;
19357                    }
19358                }
19359
19360                if (existing != null) {
19361                    if (DEBUG_PREFERRED) {
19362                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19363                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19364                    }
19365                    for (int i = 0; i < existing.size(); i++) {
19366                        PreferredActivity pa = existing.get(i);
19367                        if (DEBUG_PREFERRED) {
19368                            Slog.i(TAG, "Removing existing preferred activity "
19369                                    + pa.mPref.mComponent + ":");
19370                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19371                        }
19372                        pir.removeFilter(pa);
19373                    }
19374                }
19375            }
19376            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19377                    "Replacing preferred");
19378        }
19379    }
19380
19381    @Override
19382    public void clearPackagePreferredActivities(String packageName) {
19383        final int callingUid = Binder.getCallingUid();
19384        if (getInstantAppPackageName(callingUid) != null) {
19385            return;
19386        }
19387        // writer
19388        synchronized (mPackages) {
19389            PackageParser.Package pkg = mPackages.get(packageName);
19390            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19391                if (mContext.checkCallingOrSelfPermission(
19392                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19393                        != PackageManager.PERMISSION_GRANTED) {
19394                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19395                            < Build.VERSION_CODES.FROYO) {
19396                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19397                                + callingUid);
19398                        return;
19399                    }
19400                    mContext.enforceCallingOrSelfPermission(
19401                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19402                }
19403            }
19404            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19405            if (ps != null
19406                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19407                return;
19408            }
19409            int user = UserHandle.getCallingUserId();
19410            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19411                scheduleWritePackageRestrictionsLocked(user);
19412            }
19413        }
19414    }
19415
19416    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19417    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19418        ArrayList<PreferredActivity> removed = null;
19419        boolean changed = false;
19420        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19421            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19422            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19423            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19424                continue;
19425            }
19426            Iterator<PreferredActivity> it = pir.filterIterator();
19427            while (it.hasNext()) {
19428                PreferredActivity pa = it.next();
19429                // Mark entry for removal only if it matches the package name
19430                // and the entry is of type "always".
19431                if (packageName == null ||
19432                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19433                                && pa.mPref.mAlways)) {
19434                    if (removed == null) {
19435                        removed = new ArrayList<PreferredActivity>();
19436                    }
19437                    removed.add(pa);
19438                }
19439            }
19440            if (removed != null) {
19441                for (int j=0; j<removed.size(); j++) {
19442                    PreferredActivity pa = removed.get(j);
19443                    pir.removeFilter(pa);
19444                }
19445                changed = true;
19446            }
19447        }
19448        if (changed) {
19449            postPreferredActivityChangedBroadcast(userId);
19450        }
19451        return changed;
19452    }
19453
19454    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19455    private void clearIntentFilterVerificationsLPw(int userId) {
19456        final int packageCount = mPackages.size();
19457        for (int i = 0; i < packageCount; i++) {
19458            PackageParser.Package pkg = mPackages.valueAt(i);
19459            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19460        }
19461    }
19462
19463    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19464    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19465        if (userId == UserHandle.USER_ALL) {
19466            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19467                    sUserManager.getUserIds())) {
19468                for (int oneUserId : sUserManager.getUserIds()) {
19469                    scheduleWritePackageRestrictionsLocked(oneUserId);
19470                }
19471            }
19472        } else {
19473            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19474                scheduleWritePackageRestrictionsLocked(userId);
19475            }
19476        }
19477    }
19478
19479    /** Clears state for all users, and touches intent filter verification policy */
19480    void clearDefaultBrowserIfNeeded(String packageName) {
19481        for (int oneUserId : sUserManager.getUserIds()) {
19482            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19483        }
19484    }
19485
19486    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19487        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19488        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19489            if (packageName.equals(defaultBrowserPackageName)) {
19490                setDefaultBrowserPackageName(null, userId);
19491            }
19492        }
19493    }
19494
19495    @Override
19496    public void resetApplicationPreferences(int userId) {
19497        mContext.enforceCallingOrSelfPermission(
19498                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19499        final long identity = Binder.clearCallingIdentity();
19500        // writer
19501        try {
19502            synchronized (mPackages) {
19503                clearPackagePreferredActivitiesLPw(null, userId);
19504                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19505                // TODO: We have to reset the default SMS and Phone. This requires
19506                // significant refactoring to keep all default apps in the package
19507                // manager (cleaner but more work) or have the services provide
19508                // callbacks to the package manager to request a default app reset.
19509                applyFactoryDefaultBrowserLPw(userId);
19510                clearIntentFilterVerificationsLPw(userId);
19511                primeDomainVerificationsLPw(userId);
19512                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19513                scheduleWritePackageRestrictionsLocked(userId);
19514            }
19515            resetNetworkPolicies(userId);
19516        } finally {
19517            Binder.restoreCallingIdentity(identity);
19518        }
19519    }
19520
19521    @Override
19522    public int getPreferredActivities(List<IntentFilter> outFilters,
19523            List<ComponentName> outActivities, String packageName) {
19524        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19525            return 0;
19526        }
19527        int num = 0;
19528        final int userId = UserHandle.getCallingUserId();
19529        // reader
19530        synchronized (mPackages) {
19531            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19532            if (pir != null) {
19533                final Iterator<PreferredActivity> it = pir.filterIterator();
19534                while (it.hasNext()) {
19535                    final PreferredActivity pa = it.next();
19536                    if (packageName == null
19537                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19538                                    && pa.mPref.mAlways)) {
19539                        if (outFilters != null) {
19540                            outFilters.add(new IntentFilter(pa));
19541                        }
19542                        if (outActivities != null) {
19543                            outActivities.add(pa.mPref.mComponent);
19544                        }
19545                    }
19546                }
19547            }
19548        }
19549
19550        return num;
19551    }
19552
19553    @Override
19554    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19555            int userId) {
19556        int callingUid = Binder.getCallingUid();
19557        if (callingUid != Process.SYSTEM_UID) {
19558            throw new SecurityException(
19559                    "addPersistentPreferredActivity can only be run by the system");
19560        }
19561        if (filter.countActions() == 0) {
19562            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19563            return;
19564        }
19565        synchronized (mPackages) {
19566            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19567                    ":");
19568            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19569            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19570                    new PersistentPreferredActivity(filter, activity));
19571            scheduleWritePackageRestrictionsLocked(userId);
19572            postPreferredActivityChangedBroadcast(userId);
19573        }
19574    }
19575
19576    @Override
19577    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19578        int callingUid = Binder.getCallingUid();
19579        if (callingUid != Process.SYSTEM_UID) {
19580            throw new SecurityException(
19581                    "clearPackagePersistentPreferredActivities can only be run by the system");
19582        }
19583        ArrayList<PersistentPreferredActivity> removed = null;
19584        boolean changed = false;
19585        synchronized (mPackages) {
19586            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19587                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19588                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19589                        .valueAt(i);
19590                if (userId != thisUserId) {
19591                    continue;
19592                }
19593                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19594                while (it.hasNext()) {
19595                    PersistentPreferredActivity ppa = it.next();
19596                    // Mark entry for removal only if it matches the package name.
19597                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19598                        if (removed == null) {
19599                            removed = new ArrayList<PersistentPreferredActivity>();
19600                        }
19601                        removed.add(ppa);
19602                    }
19603                }
19604                if (removed != null) {
19605                    for (int j=0; j<removed.size(); j++) {
19606                        PersistentPreferredActivity ppa = removed.get(j);
19607                        ppir.removeFilter(ppa);
19608                    }
19609                    changed = true;
19610                }
19611            }
19612
19613            if (changed) {
19614                scheduleWritePackageRestrictionsLocked(userId);
19615                postPreferredActivityChangedBroadcast(userId);
19616            }
19617        }
19618    }
19619
19620    /**
19621     * Common machinery for picking apart a restored XML blob and passing
19622     * it to a caller-supplied functor to be applied to the running system.
19623     */
19624    private void restoreFromXml(XmlPullParser parser, int userId,
19625            String expectedStartTag, BlobXmlRestorer functor)
19626            throws IOException, XmlPullParserException {
19627        int type;
19628        while ((type = parser.next()) != XmlPullParser.START_TAG
19629                && type != XmlPullParser.END_DOCUMENT) {
19630        }
19631        if (type != XmlPullParser.START_TAG) {
19632            // oops didn't find a start tag?!
19633            if (DEBUG_BACKUP) {
19634                Slog.e(TAG, "Didn't find start tag during restore");
19635            }
19636            return;
19637        }
19638Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19639        // this is supposed to be TAG_PREFERRED_BACKUP
19640        if (!expectedStartTag.equals(parser.getName())) {
19641            if (DEBUG_BACKUP) {
19642                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19643            }
19644            return;
19645        }
19646
19647        // skip interfering stuff, then we're aligned with the backing implementation
19648        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19649Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19650        functor.apply(parser, userId);
19651    }
19652
19653    private interface BlobXmlRestorer {
19654        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19655    }
19656
19657    /**
19658     * Non-Binder method, support for the backup/restore mechanism: write the
19659     * full set of preferred activities in its canonical XML format.  Returns the
19660     * XML output as a byte array, or null if there is none.
19661     */
19662    @Override
19663    public byte[] getPreferredActivityBackup(int userId) {
19664        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19665            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19666        }
19667
19668        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19669        try {
19670            final XmlSerializer serializer = new FastXmlSerializer();
19671            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19672            serializer.startDocument(null, true);
19673            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19674
19675            synchronized (mPackages) {
19676                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19677            }
19678
19679            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19680            serializer.endDocument();
19681            serializer.flush();
19682        } catch (Exception e) {
19683            if (DEBUG_BACKUP) {
19684                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19685            }
19686            return null;
19687        }
19688
19689        return dataStream.toByteArray();
19690    }
19691
19692    @Override
19693    public void restorePreferredActivities(byte[] backup, int userId) {
19694        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19695            throw new SecurityException("Only the system may call restorePreferredActivities()");
19696        }
19697
19698        try {
19699            final XmlPullParser parser = Xml.newPullParser();
19700            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19701            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19702                    new BlobXmlRestorer() {
19703                        @Override
19704                        public void apply(XmlPullParser parser, int userId)
19705                                throws XmlPullParserException, IOException {
19706                            synchronized (mPackages) {
19707                                mSettings.readPreferredActivitiesLPw(parser, userId);
19708                            }
19709                        }
19710                    } );
19711        } catch (Exception e) {
19712            if (DEBUG_BACKUP) {
19713                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19714            }
19715        }
19716    }
19717
19718    /**
19719     * Non-Binder method, support for the backup/restore mechanism: write the
19720     * default browser (etc) settings in its canonical XML format.  Returns the default
19721     * browser XML representation as a byte array, or null if there is none.
19722     */
19723    @Override
19724    public byte[] getDefaultAppsBackup(int userId) {
19725        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19726            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19727        }
19728
19729        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19730        try {
19731            final XmlSerializer serializer = new FastXmlSerializer();
19732            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19733            serializer.startDocument(null, true);
19734            serializer.startTag(null, TAG_DEFAULT_APPS);
19735
19736            synchronized (mPackages) {
19737                mSettings.writeDefaultAppsLPr(serializer, userId);
19738            }
19739
19740            serializer.endTag(null, TAG_DEFAULT_APPS);
19741            serializer.endDocument();
19742            serializer.flush();
19743        } catch (Exception e) {
19744            if (DEBUG_BACKUP) {
19745                Slog.e(TAG, "Unable to write default apps for backup", e);
19746            }
19747            return null;
19748        }
19749
19750        return dataStream.toByteArray();
19751    }
19752
19753    @Override
19754    public void restoreDefaultApps(byte[] backup, int userId) {
19755        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19756            throw new SecurityException("Only the system may call restoreDefaultApps()");
19757        }
19758
19759        try {
19760            final XmlPullParser parser = Xml.newPullParser();
19761            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19762            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19763                    new BlobXmlRestorer() {
19764                        @Override
19765                        public void apply(XmlPullParser parser, int userId)
19766                                throws XmlPullParserException, IOException {
19767                            synchronized (mPackages) {
19768                                mSettings.readDefaultAppsLPw(parser, userId);
19769                            }
19770                        }
19771                    } );
19772        } catch (Exception e) {
19773            if (DEBUG_BACKUP) {
19774                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19775            }
19776        }
19777    }
19778
19779    @Override
19780    public byte[] getIntentFilterVerificationBackup(int userId) {
19781        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19782            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19783        }
19784
19785        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19786        try {
19787            final XmlSerializer serializer = new FastXmlSerializer();
19788            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19789            serializer.startDocument(null, true);
19790            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19791
19792            synchronized (mPackages) {
19793                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19794            }
19795
19796            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19797            serializer.endDocument();
19798            serializer.flush();
19799        } catch (Exception e) {
19800            if (DEBUG_BACKUP) {
19801                Slog.e(TAG, "Unable to write default apps for backup", e);
19802            }
19803            return null;
19804        }
19805
19806        return dataStream.toByteArray();
19807    }
19808
19809    @Override
19810    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19811        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19812            throw new SecurityException("Only the system may call restorePreferredActivities()");
19813        }
19814
19815        try {
19816            final XmlPullParser parser = Xml.newPullParser();
19817            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19818            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19819                    new BlobXmlRestorer() {
19820                        @Override
19821                        public void apply(XmlPullParser parser, int userId)
19822                                throws XmlPullParserException, IOException {
19823                            synchronized (mPackages) {
19824                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19825                                mSettings.writeLPr();
19826                            }
19827                        }
19828                    } );
19829        } catch (Exception e) {
19830            if (DEBUG_BACKUP) {
19831                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19832            }
19833        }
19834    }
19835
19836    @Override
19837    public byte[] getPermissionGrantBackup(int userId) {
19838        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19839            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19840        }
19841
19842        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19843        try {
19844            final XmlSerializer serializer = new FastXmlSerializer();
19845            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19846            serializer.startDocument(null, true);
19847            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19848
19849            synchronized (mPackages) {
19850                serializeRuntimePermissionGrantsLPr(serializer, userId);
19851            }
19852
19853            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19854            serializer.endDocument();
19855            serializer.flush();
19856        } catch (Exception e) {
19857            if (DEBUG_BACKUP) {
19858                Slog.e(TAG, "Unable to write default apps for backup", e);
19859            }
19860            return null;
19861        }
19862
19863        return dataStream.toByteArray();
19864    }
19865
19866    @Override
19867    public void restorePermissionGrants(byte[] backup, int userId) {
19868        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19869            throw new SecurityException("Only the system may call restorePermissionGrants()");
19870        }
19871
19872        try {
19873            final XmlPullParser parser = Xml.newPullParser();
19874            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19875            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19876                    new BlobXmlRestorer() {
19877                        @Override
19878                        public void apply(XmlPullParser parser, int userId)
19879                                throws XmlPullParserException, IOException {
19880                            synchronized (mPackages) {
19881                                processRestoredPermissionGrantsLPr(parser, userId);
19882                            }
19883                        }
19884                    } );
19885        } catch (Exception e) {
19886            if (DEBUG_BACKUP) {
19887                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19888            }
19889        }
19890    }
19891
19892    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19893            throws IOException {
19894        serializer.startTag(null, TAG_ALL_GRANTS);
19895
19896        final int N = mSettings.mPackages.size();
19897        for (int i = 0; i < N; i++) {
19898            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19899            boolean pkgGrantsKnown = false;
19900
19901            PermissionsState packagePerms = ps.getPermissionsState();
19902
19903            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19904                final int grantFlags = state.getFlags();
19905                // only look at grants that are not system/policy fixed
19906                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19907                    final boolean isGranted = state.isGranted();
19908                    // And only back up the user-twiddled state bits
19909                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19910                        final String packageName = mSettings.mPackages.keyAt(i);
19911                        if (!pkgGrantsKnown) {
19912                            serializer.startTag(null, TAG_GRANT);
19913                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19914                            pkgGrantsKnown = true;
19915                        }
19916
19917                        final boolean userSet =
19918                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19919                        final boolean userFixed =
19920                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19921                        final boolean revoke =
19922                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19923
19924                        serializer.startTag(null, TAG_PERMISSION);
19925                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19926                        if (isGranted) {
19927                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19928                        }
19929                        if (userSet) {
19930                            serializer.attribute(null, ATTR_USER_SET, "true");
19931                        }
19932                        if (userFixed) {
19933                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19934                        }
19935                        if (revoke) {
19936                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19937                        }
19938                        serializer.endTag(null, TAG_PERMISSION);
19939                    }
19940                }
19941            }
19942
19943            if (pkgGrantsKnown) {
19944                serializer.endTag(null, TAG_GRANT);
19945            }
19946        }
19947
19948        serializer.endTag(null, TAG_ALL_GRANTS);
19949    }
19950
19951    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19952            throws XmlPullParserException, IOException {
19953        String pkgName = null;
19954        int outerDepth = parser.getDepth();
19955        int type;
19956        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19957                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19958            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19959                continue;
19960            }
19961
19962            final String tagName = parser.getName();
19963            if (tagName.equals(TAG_GRANT)) {
19964                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19965                if (DEBUG_BACKUP) {
19966                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19967                }
19968            } else if (tagName.equals(TAG_PERMISSION)) {
19969
19970                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19971                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19972
19973                int newFlagSet = 0;
19974                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19975                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19976                }
19977                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19978                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19979                }
19980                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19981                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19982                }
19983                if (DEBUG_BACKUP) {
19984                    Slog.v(TAG, "  + Restoring grant:"
19985                            + " pkg=" + pkgName
19986                            + " perm=" + permName
19987                            + " granted=" + isGranted
19988                            + " bits=0x" + Integer.toHexString(newFlagSet));
19989                }
19990                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19991                if (ps != null) {
19992                    // Already installed so we apply the grant immediately
19993                    if (DEBUG_BACKUP) {
19994                        Slog.v(TAG, "        + already installed; applying");
19995                    }
19996                    PermissionsState perms = ps.getPermissionsState();
19997                    BasePermission bp =
19998                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19999                    if (bp != null) {
20000                        if (isGranted) {
20001                            perms.grantRuntimePermission(bp, userId);
20002                        }
20003                        if (newFlagSet != 0) {
20004                            perms.updatePermissionFlags(
20005                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20006                        }
20007                    }
20008                } else {
20009                    // Need to wait for post-restore install to apply the grant
20010                    if (DEBUG_BACKUP) {
20011                        Slog.v(TAG, "        - not yet installed; saving for later");
20012                    }
20013                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20014                            isGranted, newFlagSet, userId);
20015                }
20016            } else {
20017                PackageManagerService.reportSettingsProblem(Log.WARN,
20018                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20019                XmlUtils.skipCurrentTag(parser);
20020            }
20021        }
20022
20023        scheduleWriteSettingsLocked();
20024        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20025    }
20026
20027    @Override
20028    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20029            int sourceUserId, int targetUserId, int flags) {
20030        mContext.enforceCallingOrSelfPermission(
20031                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20032        int callingUid = Binder.getCallingUid();
20033        enforceOwnerRights(ownerPackage, callingUid);
20034        PackageManagerServiceUtils.enforceShellRestriction(
20035                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20036        if (intentFilter.countActions() == 0) {
20037            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20038            return;
20039        }
20040        synchronized (mPackages) {
20041            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20042                    ownerPackage, targetUserId, flags);
20043            CrossProfileIntentResolver resolver =
20044                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20045            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20046            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20047            if (existing != null) {
20048                int size = existing.size();
20049                for (int i = 0; i < size; i++) {
20050                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20051                        return;
20052                    }
20053                }
20054            }
20055            resolver.addFilter(newFilter);
20056            scheduleWritePackageRestrictionsLocked(sourceUserId);
20057        }
20058    }
20059
20060    @Override
20061    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20062        mContext.enforceCallingOrSelfPermission(
20063                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20064        final int callingUid = Binder.getCallingUid();
20065        enforceOwnerRights(ownerPackage, callingUid);
20066        PackageManagerServiceUtils.enforceShellRestriction(
20067                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20068        synchronized (mPackages) {
20069            CrossProfileIntentResolver resolver =
20070                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20071            ArraySet<CrossProfileIntentFilter> set =
20072                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20073            for (CrossProfileIntentFilter filter : set) {
20074                if (filter.getOwnerPackage().equals(ownerPackage)) {
20075                    resolver.removeFilter(filter);
20076                }
20077            }
20078            scheduleWritePackageRestrictionsLocked(sourceUserId);
20079        }
20080    }
20081
20082    // Enforcing that callingUid is owning pkg on userId
20083    private void enforceOwnerRights(String pkg, int callingUid) {
20084        // The system owns everything.
20085        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20086            return;
20087        }
20088        final int callingUserId = UserHandle.getUserId(callingUid);
20089        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20090        if (pi == null) {
20091            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20092                    + callingUserId);
20093        }
20094        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20095            throw new SecurityException("Calling uid " + callingUid
20096                    + " does not own package " + pkg);
20097        }
20098    }
20099
20100    @Override
20101    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20102        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20103            return null;
20104        }
20105        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20106    }
20107
20108    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20109        UserManagerService ums = UserManagerService.getInstance();
20110        if (ums != null) {
20111            final UserInfo parent = ums.getProfileParent(userId);
20112            final int launcherUid = (parent != null) ? parent.id : userId;
20113            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20114            if (launcherComponent != null) {
20115                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20116                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20117                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20118                        .setPackage(launcherComponent.getPackageName());
20119                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20120            }
20121        }
20122    }
20123
20124    /**
20125     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20126     * then reports the most likely home activity or null if there are more than one.
20127     */
20128    private ComponentName getDefaultHomeActivity(int userId) {
20129        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20130        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20131        if (cn != null) {
20132            return cn;
20133        }
20134
20135        // Find the launcher with the highest priority and return that component if there are no
20136        // other home activity with the same priority.
20137        int lastPriority = Integer.MIN_VALUE;
20138        ComponentName lastComponent = null;
20139        final int size = allHomeCandidates.size();
20140        for (int i = 0; i < size; i++) {
20141            final ResolveInfo ri = allHomeCandidates.get(i);
20142            if (ri.priority > lastPriority) {
20143                lastComponent = ri.activityInfo.getComponentName();
20144                lastPriority = ri.priority;
20145            } else if (ri.priority == lastPriority) {
20146                // Two components found with same priority.
20147                lastComponent = null;
20148            }
20149        }
20150        return lastComponent;
20151    }
20152
20153    private Intent getHomeIntent() {
20154        Intent intent = new Intent(Intent.ACTION_MAIN);
20155        intent.addCategory(Intent.CATEGORY_HOME);
20156        intent.addCategory(Intent.CATEGORY_DEFAULT);
20157        return intent;
20158    }
20159
20160    private IntentFilter getHomeFilter() {
20161        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20162        filter.addCategory(Intent.CATEGORY_HOME);
20163        filter.addCategory(Intent.CATEGORY_DEFAULT);
20164        return filter;
20165    }
20166
20167    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20168            int userId) {
20169        Intent intent  = getHomeIntent();
20170        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20171                PackageManager.GET_META_DATA, userId);
20172        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20173                true, false, false, userId);
20174
20175        allHomeCandidates.clear();
20176        if (list != null) {
20177            for (ResolveInfo ri : list) {
20178                allHomeCandidates.add(ri);
20179            }
20180        }
20181        return (preferred == null || preferred.activityInfo == null)
20182                ? null
20183                : new ComponentName(preferred.activityInfo.packageName,
20184                        preferred.activityInfo.name);
20185    }
20186
20187    @Override
20188    public void setHomeActivity(ComponentName comp, int userId) {
20189        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20190            return;
20191        }
20192        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20193        getHomeActivitiesAsUser(homeActivities, userId);
20194
20195        boolean found = false;
20196
20197        final int size = homeActivities.size();
20198        final ComponentName[] set = new ComponentName[size];
20199        for (int i = 0; i < size; i++) {
20200            final ResolveInfo candidate = homeActivities.get(i);
20201            final ActivityInfo info = candidate.activityInfo;
20202            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20203            set[i] = activityName;
20204            if (!found && activityName.equals(comp)) {
20205                found = true;
20206            }
20207        }
20208        if (!found) {
20209            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20210                    + userId);
20211        }
20212        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20213                set, comp, userId);
20214    }
20215
20216    private @Nullable String getSetupWizardPackageName() {
20217        final Intent intent = new Intent(Intent.ACTION_MAIN);
20218        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
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 setup wizard; found " + matches.size()
20228                    + ": matches=" + matches);
20229            return null;
20230        }
20231    }
20232
20233    private @Nullable String getStorageManagerPackageName() {
20234        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20235
20236        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20237                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20238                        | MATCH_DISABLED_COMPONENTS,
20239                UserHandle.myUserId());
20240        if (matches.size() == 1) {
20241            return matches.get(0).getComponentInfo().packageName;
20242        } else {
20243            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20244                    + matches.size() + ": matches=" + matches);
20245            return null;
20246        }
20247    }
20248
20249    @Override
20250    public void setApplicationEnabledSetting(String appPackageName,
20251            int newState, int flags, int userId, String callingPackage) {
20252        if (!sUserManager.exists(userId)) return;
20253        if (callingPackage == null) {
20254            callingPackage = Integer.toString(Binder.getCallingUid());
20255        }
20256        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20257    }
20258
20259    @Override
20260    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20261        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20262        synchronized (mPackages) {
20263            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20264            if (pkgSetting != null) {
20265                pkgSetting.setUpdateAvailable(updateAvailable);
20266            }
20267        }
20268    }
20269
20270    @Override
20271    public void setComponentEnabledSetting(ComponentName componentName,
20272            int newState, int flags, int userId) {
20273        if (!sUserManager.exists(userId)) return;
20274        setEnabledSetting(componentName.getPackageName(),
20275                componentName.getClassName(), newState, flags, userId, null);
20276    }
20277
20278    private void setEnabledSetting(final String packageName, String className, int newState,
20279            final int flags, int userId, String callingPackage) {
20280        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20281              || newState == COMPONENT_ENABLED_STATE_ENABLED
20282              || newState == COMPONENT_ENABLED_STATE_DISABLED
20283              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20284              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20285            throw new IllegalArgumentException("Invalid new component state: "
20286                    + newState);
20287        }
20288        PackageSetting pkgSetting;
20289        final int callingUid = Binder.getCallingUid();
20290        final int permission;
20291        if (callingUid == Process.SYSTEM_UID) {
20292            permission = PackageManager.PERMISSION_GRANTED;
20293        } else {
20294            permission = mContext.checkCallingOrSelfPermission(
20295                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20296        }
20297        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20298                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20299        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20300        boolean sendNow = false;
20301        boolean isApp = (className == null);
20302        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20303        String componentName = isApp ? packageName : className;
20304        int packageUid = -1;
20305        ArrayList<String> components;
20306
20307        // reader
20308        synchronized (mPackages) {
20309            pkgSetting = mSettings.mPackages.get(packageName);
20310            if (pkgSetting == null) {
20311                if (!isCallerInstantApp) {
20312                    if (className == null) {
20313                        throw new IllegalArgumentException("Unknown package: " + packageName);
20314                    }
20315                    throw new IllegalArgumentException(
20316                            "Unknown component: " + packageName + "/" + className);
20317                } else {
20318                    // throw SecurityException to prevent leaking package information
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            }
20328        }
20329
20330        // Limit who can change which apps
20331        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20332            // Don't allow apps that don't have permission to modify other apps
20333            if (!allowedByPermission
20334                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20335                throw new SecurityException(
20336                        "Attempt to change component state; "
20337                        + "pid=" + Binder.getCallingPid()
20338                        + ", uid=" + callingUid
20339                        + (className == null
20340                                ? ", package=" + packageName
20341                                : ", component=" + packageName + "/" + className));
20342            }
20343            // Don't allow changing protected packages.
20344            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20345                throw new SecurityException("Cannot disable a protected package: " + packageName);
20346            }
20347        }
20348
20349        synchronized (mPackages) {
20350            if (callingUid == Process.SHELL_UID
20351                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20352                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20353                // unless it is a test package.
20354                int oldState = pkgSetting.getEnabled(userId);
20355                if (className == null
20356                        &&
20357                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20358                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20359                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20360                        &&
20361                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20362                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20363                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20364                    // ok
20365                } else {
20366                    throw new SecurityException(
20367                            "Shell cannot change component state for " + packageName + "/"
20368                                    + className + " to " + newState);
20369                }
20370            }
20371        }
20372        if (className == null) {
20373            // We're dealing with an application/package level state change
20374            synchronized (mPackages) {
20375                if (pkgSetting.getEnabled(userId) == newState) {
20376                    // Nothing to do
20377                    return;
20378                }
20379            }
20380            // If we're enabling a system stub, there's a little more work to do.
20381            // Prior to enabling the package, we need to decompress the APK(s) to the
20382            // data partition and then replace the version on the system partition.
20383            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20384            final boolean isSystemStub = deletedPkg.isStub
20385                    && deletedPkg.isSystem();
20386            if (isSystemStub
20387                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20388                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20389                final File codePath = decompressPackage(deletedPkg);
20390                if (codePath == null) {
20391                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20392                    return;
20393                }
20394                // TODO remove direct parsing of the package object during internal cleanup
20395                // of scan package
20396                // We need to call parse directly here for no other reason than we need
20397                // the new package in order to disable the old one [we use the information
20398                // for some internal optimization to optionally create a new package setting
20399                // object on replace]. However, we can't get the package from the scan
20400                // because the scan modifies live structures and we need to remove the
20401                // old [system] package from the system before a scan can be attempted.
20402                // Once scan is indempotent we can remove this parse and use the package
20403                // object we scanned, prior to adding it to package settings.
20404                final PackageParser pp = new PackageParser();
20405                pp.setSeparateProcesses(mSeparateProcesses);
20406                pp.setDisplayMetrics(mMetrics);
20407                pp.setCallback(mPackageParserCallback);
20408                final PackageParser.Package tmpPkg;
20409                try {
20410                    final @ParseFlags int parseFlags = mDefParseFlags
20411                            | PackageParser.PARSE_MUST_BE_APK
20412                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20413                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20414                } catch (PackageParserException e) {
20415                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20416                    return;
20417                }
20418                synchronized (mInstallLock) {
20419                    // Disable the stub and remove any package entries
20420                    removePackageLI(deletedPkg, true);
20421                    synchronized (mPackages) {
20422                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20423                    }
20424                    final PackageParser.Package pkg;
20425                    try (PackageFreezer freezer =
20426                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20427                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20428                                | PackageParser.PARSE_ENFORCE_CODE;
20429                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20430                                0 /*currentTime*/, null /*user*/);
20431                        prepareAppDataAfterInstallLIF(pkg);
20432                        synchronized (mPackages) {
20433                            try {
20434                                updateSharedLibrariesLPr(pkg, null);
20435                            } catch (PackageManagerException e) {
20436                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20437                            }
20438                            mPermissionManager.updatePermissions(
20439                                    pkg.packageName, pkg, true, mPackages.values(),
20440                                    mPermissionCallback);
20441                            mSettings.writeLPr();
20442                        }
20443                    } catch (PackageManagerException e) {
20444                        // Whoops! Something went wrong; try to roll back to the stub
20445                        Slog.w(TAG, "Failed to install compressed system package:"
20446                                + pkgSetting.name, e);
20447                        // Remove the failed install
20448                        removeCodePathLI(codePath);
20449
20450                        // Install the system package
20451                        try (PackageFreezer freezer =
20452                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20453                            synchronized (mPackages) {
20454                                // NOTE: The system package always needs to be enabled; even
20455                                // if it's for a compressed stub. If we don't, installing the
20456                                // system package fails during scan [scanning checks the disabled
20457                                // packages]. We will reverse this later, after we've "installed"
20458                                // the stub.
20459                                // This leaves us in a fragile state; the stub should never be
20460                                // enabled, so, cross your fingers and hope nothing goes wrong
20461                                // until we can disable the package later.
20462                                enableSystemPackageLPw(deletedPkg);
20463                            }
20464                            installPackageFromSystemLIF(deletedPkg.codePath,
20465                                    false /*isPrivileged*/, null /*allUserHandles*/,
20466                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20467                                    true /*writeSettings*/);
20468                        } catch (PackageManagerException pme) {
20469                            Slog.w(TAG, "Failed to restore system package:"
20470                                    + deletedPkg.packageName, pme);
20471                        } finally {
20472                            synchronized (mPackages) {
20473                                mSettings.disableSystemPackageLPw(
20474                                        deletedPkg.packageName, true /*replaced*/);
20475                                mSettings.writeLPr();
20476                            }
20477                        }
20478                        return;
20479                    }
20480                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20481                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20482                    mDexManager.notifyPackageUpdated(pkg.packageName,
20483                            pkg.baseCodePath, pkg.splitCodePaths);
20484                }
20485            }
20486            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20487                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20488                // Don't care about who enables an app.
20489                callingPackage = null;
20490            }
20491            synchronized (mPackages) {
20492                pkgSetting.setEnabled(newState, userId, callingPackage);
20493            }
20494        } else {
20495            synchronized (mPackages) {
20496                // We're dealing with a component level state change
20497                // First, verify that this is a valid class name.
20498                PackageParser.Package pkg = pkgSetting.pkg;
20499                if (pkg == null || !pkg.hasComponentClassName(className)) {
20500                    if (pkg != null &&
20501                            pkg.applicationInfo.targetSdkVersion >=
20502                                    Build.VERSION_CODES.JELLY_BEAN) {
20503                        throw new IllegalArgumentException("Component class " + className
20504                                + " does not exist in " + packageName);
20505                    } else {
20506                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20507                                + className + " does not exist in " + packageName);
20508                    }
20509                }
20510                switch (newState) {
20511                    case COMPONENT_ENABLED_STATE_ENABLED:
20512                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20513                            return;
20514                        }
20515                        break;
20516                    case COMPONENT_ENABLED_STATE_DISABLED:
20517                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20518                            return;
20519                        }
20520                        break;
20521                    case COMPONENT_ENABLED_STATE_DEFAULT:
20522                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20523                            return;
20524                        }
20525                        break;
20526                    default:
20527                        Slog.e(TAG, "Invalid new component state: " + newState);
20528                        return;
20529                }
20530            }
20531        }
20532        synchronized (mPackages) {
20533            scheduleWritePackageRestrictionsLocked(userId);
20534            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20535            final long callingId = Binder.clearCallingIdentity();
20536            try {
20537                updateInstantAppInstallerLocked(packageName);
20538            } finally {
20539                Binder.restoreCallingIdentity(callingId);
20540            }
20541            components = mPendingBroadcasts.get(userId, packageName);
20542            final boolean newPackage = components == null;
20543            if (newPackage) {
20544                components = new ArrayList<String>();
20545            }
20546            if (!components.contains(componentName)) {
20547                components.add(componentName);
20548            }
20549            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20550                sendNow = true;
20551                // Purge entry from pending broadcast list if another one exists already
20552                // since we are sending one right away.
20553                mPendingBroadcasts.remove(userId, packageName);
20554            } else {
20555                if (newPackage) {
20556                    mPendingBroadcasts.put(userId, packageName, components);
20557                }
20558                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20559                    // Schedule a message
20560                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20561                }
20562            }
20563        }
20564
20565        long callingId = Binder.clearCallingIdentity();
20566        try {
20567            if (sendNow) {
20568                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20569                sendPackageChangedBroadcast(packageName,
20570                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20571            }
20572        } finally {
20573            Binder.restoreCallingIdentity(callingId);
20574        }
20575    }
20576
20577    @Override
20578    public void flushPackageRestrictionsAsUser(int userId) {
20579        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20580            return;
20581        }
20582        if (!sUserManager.exists(userId)) {
20583            return;
20584        }
20585        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20586                false /* checkShell */, "flushPackageRestrictions");
20587        synchronized (mPackages) {
20588            mSettings.writePackageRestrictionsLPr(userId);
20589            mDirtyUsers.remove(userId);
20590            if (mDirtyUsers.isEmpty()) {
20591                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20592            }
20593        }
20594    }
20595
20596    private void sendPackageChangedBroadcast(String packageName,
20597            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20598        if (DEBUG_INSTALL)
20599            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20600                    + componentNames);
20601        Bundle extras = new Bundle(4);
20602        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20603        String nameList[] = new String[componentNames.size()];
20604        componentNames.toArray(nameList);
20605        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20606        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20607        extras.putInt(Intent.EXTRA_UID, packageUid);
20608        // If this is not reporting a change of the overall package, then only send it
20609        // to registered receivers.  We don't want to launch a swath of apps for every
20610        // little component state change.
20611        final int flags = !componentNames.contains(packageName)
20612                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20613        final int userId = UserHandle.getUserId(packageUid);
20614        final boolean isInstantApp = isInstantApp(packageName, userId);
20615        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20616        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20617        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20618                userIds, instantUserIds);
20619    }
20620
20621    @Override
20622    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20623        if (!sUserManager.exists(userId)) return;
20624        final int callingUid = Binder.getCallingUid();
20625        if (getInstantAppPackageName(callingUid) != null) {
20626            return;
20627        }
20628        final int permission = mContext.checkCallingOrSelfPermission(
20629                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20630        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20631        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20632                true /* requireFullPermission */, true /* checkShell */, "stop package");
20633        // writer
20634        synchronized (mPackages) {
20635            final PackageSetting ps = mSettings.mPackages.get(packageName);
20636            if (!filterAppAccessLPr(ps, callingUid, userId)
20637                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20638                            allowedByPermission, callingUid, userId)) {
20639                scheduleWritePackageRestrictionsLocked(userId);
20640            }
20641        }
20642    }
20643
20644    @Override
20645    public String getInstallerPackageName(String packageName) {
20646        final int callingUid = Binder.getCallingUid();
20647        if (getInstantAppPackageName(callingUid) != null) {
20648            return null;
20649        }
20650        // reader
20651        synchronized (mPackages) {
20652            final PackageSetting ps = mSettings.mPackages.get(packageName);
20653            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20654                return null;
20655            }
20656            return mSettings.getInstallerPackageNameLPr(packageName);
20657        }
20658    }
20659
20660    public boolean isOrphaned(String packageName) {
20661        // reader
20662        synchronized (mPackages) {
20663            return mSettings.isOrphaned(packageName);
20664        }
20665    }
20666
20667    @Override
20668    public int getApplicationEnabledSetting(String packageName, int userId) {
20669        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20670        int callingUid = Binder.getCallingUid();
20671        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20672                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20673        // reader
20674        synchronized (mPackages) {
20675            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20676                return COMPONENT_ENABLED_STATE_DISABLED;
20677            }
20678            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20679        }
20680    }
20681
20682    @Override
20683    public int getComponentEnabledSetting(ComponentName component, int userId) {
20684        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20685        int callingUid = Binder.getCallingUid();
20686        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20687                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20688        synchronized (mPackages) {
20689            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20690                    component, TYPE_UNKNOWN, userId)) {
20691                return COMPONENT_ENABLED_STATE_DISABLED;
20692            }
20693            return mSettings.getComponentEnabledSettingLPr(component, userId);
20694        }
20695    }
20696
20697    @Override
20698    public void enterSafeMode() {
20699        enforceSystemOrRoot("Only the system can request entering safe mode");
20700
20701        if (!mSystemReady) {
20702            mSafeMode = true;
20703        }
20704    }
20705
20706    @Override
20707    public void systemReady() {
20708        enforceSystemOrRoot("Only the system can claim the system is ready");
20709
20710        mSystemReady = true;
20711        final ContentResolver resolver = mContext.getContentResolver();
20712        ContentObserver co = new ContentObserver(mHandler) {
20713            @Override
20714            public void onChange(boolean selfChange) {
20715                mWebInstantAppsDisabled =
20716                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20717                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20718            }
20719        };
20720        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20721                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20722                false, co, UserHandle.USER_SYSTEM);
20723        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20724                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20725        co.onChange(true);
20726
20727        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20728        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20729        // it is done.
20730        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20731            @Override
20732            public void onChange(boolean selfChange) {
20733                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20734                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20735                        oobEnabled == 1 ? "true" : "false");
20736            }
20737        };
20738        mContext.getContentResolver().registerContentObserver(
20739                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20740                UserHandle.USER_SYSTEM);
20741        // At boot, restore the value from the setting, which persists across reboot.
20742        privAppOobObserver.onChange(true);
20743
20744        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20745        // disabled after already being started.
20746        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20747                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20748
20749        // Read the compatibilty setting when the system is ready.
20750        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20751                mContext.getContentResolver(),
20752                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20753        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20754        if (DEBUG_SETTINGS) {
20755            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20756        }
20757
20758        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20759
20760        synchronized (mPackages) {
20761            // Verify that all of the preferred activity components actually
20762            // exist.  It is possible for applications to be updated and at
20763            // that point remove a previously declared activity component that
20764            // had been set as a preferred activity.  We try to clean this up
20765            // the next time we encounter that preferred activity, but it is
20766            // possible for the user flow to never be able to return to that
20767            // situation so here we do a sanity check to make sure we haven't
20768            // left any junk around.
20769            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20770            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20771                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20772                removed.clear();
20773                for (PreferredActivity pa : pir.filterSet()) {
20774                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20775                        removed.add(pa);
20776                    }
20777                }
20778                if (removed.size() > 0) {
20779                    for (int r=0; r<removed.size(); r++) {
20780                        PreferredActivity pa = removed.get(r);
20781                        Slog.w(TAG, "Removing dangling preferred activity: "
20782                                + pa.mPref.mComponent);
20783                        pir.removeFilter(pa);
20784                    }
20785                    mSettings.writePackageRestrictionsLPr(
20786                            mSettings.mPreferredActivities.keyAt(i));
20787                }
20788            }
20789
20790            for (int userId : UserManagerService.getInstance().getUserIds()) {
20791                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20792                    grantPermissionsUserIds = ArrayUtils.appendInt(
20793                            grantPermissionsUserIds, userId);
20794                }
20795            }
20796        }
20797        sUserManager.systemReady();
20798        // If we upgraded grant all default permissions before kicking off.
20799        for (int userId : grantPermissionsUserIds) {
20800            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20801        }
20802
20803        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20804            // If we did not grant default permissions, we preload from this the
20805            // default permission exceptions lazily to ensure we don't hit the
20806            // disk on a new user creation.
20807            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20808        }
20809
20810        // Now that we've scanned all packages, and granted any default
20811        // permissions, ensure permissions are updated. Beware of dragons if you
20812        // try optimizing this.
20813        synchronized (mPackages) {
20814            mPermissionManager.updateAllPermissions(
20815                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20816                    mPermissionCallback);
20817        }
20818
20819        // Kick off any messages waiting for system ready
20820        if (mPostSystemReadyMessages != null) {
20821            for (Message msg : mPostSystemReadyMessages) {
20822                msg.sendToTarget();
20823            }
20824            mPostSystemReadyMessages = null;
20825        }
20826
20827        // Watch for external volumes that come and go over time
20828        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20829        storage.registerListener(mStorageListener);
20830
20831        mInstallerService.systemReady();
20832        mPackageDexOptimizer.systemReady();
20833
20834        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20835                StorageManagerInternal.class);
20836        StorageManagerInternal.addExternalStoragePolicy(
20837                new StorageManagerInternal.ExternalStorageMountPolicy() {
20838            @Override
20839            public int getMountMode(int uid, String packageName) {
20840                if (Process.isIsolated(uid)) {
20841                    return Zygote.MOUNT_EXTERNAL_NONE;
20842                }
20843                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20844                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20845                }
20846                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20847                    return Zygote.MOUNT_EXTERNAL_READ;
20848                }
20849                return Zygote.MOUNT_EXTERNAL_WRITE;
20850            }
20851
20852            @Override
20853            public boolean hasExternalStorage(int uid, String packageName) {
20854                return true;
20855            }
20856        });
20857
20858        // Now that we're mostly running, clean up stale users and apps
20859        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20860        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20861
20862        mPermissionManager.systemReady();
20863    }
20864
20865    public void waitForAppDataPrepared() {
20866        if (mPrepareAppDataFuture == null) {
20867            return;
20868        }
20869        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20870        mPrepareAppDataFuture = null;
20871    }
20872
20873    @Override
20874    public boolean isSafeMode() {
20875        // allow instant applications
20876        return mSafeMode;
20877    }
20878
20879    @Override
20880    public boolean hasSystemUidErrors() {
20881        // allow instant applications
20882        return mHasSystemUidErrors;
20883    }
20884
20885    static String arrayToString(int[] array) {
20886        StringBuffer buf = new StringBuffer(128);
20887        buf.append('[');
20888        if (array != null) {
20889            for (int i=0; i<array.length; i++) {
20890                if (i > 0) buf.append(", ");
20891                buf.append(array[i]);
20892            }
20893        }
20894        buf.append(']');
20895        return buf.toString();
20896    }
20897
20898    @Override
20899    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20900            FileDescriptor err, String[] args, ShellCallback callback,
20901            ResultReceiver resultReceiver) {
20902        (new PackageManagerShellCommand(this)).exec(
20903                this, in, out, err, args, callback, resultReceiver);
20904    }
20905
20906    @Override
20907    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20908        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20909
20910        DumpState dumpState = new DumpState();
20911        boolean fullPreferred = false;
20912        boolean checkin = false;
20913
20914        String packageName = null;
20915        ArraySet<String> permissionNames = null;
20916
20917        int opti = 0;
20918        while (opti < args.length) {
20919            String opt = args[opti];
20920            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20921                break;
20922            }
20923            opti++;
20924
20925            if ("-a".equals(opt)) {
20926                // Right now we only know how to print all.
20927            } else if ("-h".equals(opt)) {
20928                pw.println("Package manager dump options:");
20929                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20930                pw.println("    --checkin: dump for a checkin");
20931                pw.println("    -f: print details of intent filters");
20932                pw.println("    -h: print this help");
20933                pw.println("  cmd may be one of:");
20934                pw.println("    l[ibraries]: list known shared libraries");
20935                pw.println("    f[eatures]: list device features");
20936                pw.println("    k[eysets]: print known keysets");
20937                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20938                pw.println("    perm[issions]: dump permissions");
20939                pw.println("    permission [name ...]: dump declaration and use of given permission");
20940                pw.println("    pref[erred]: print preferred package settings");
20941                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20942                pw.println("    prov[iders]: dump content providers");
20943                pw.println("    p[ackages]: dump installed packages");
20944                pw.println("    s[hared-users]: dump shared user IDs");
20945                pw.println("    m[essages]: print collected runtime messages");
20946                pw.println("    v[erifiers]: print package verifier info");
20947                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20948                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20949                pw.println("    version: print database version info");
20950                pw.println("    write: write current settings now");
20951                pw.println("    installs: details about install sessions");
20952                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20953                pw.println("    dexopt: dump dexopt state");
20954                pw.println("    compiler-stats: dump compiler statistics");
20955                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20956                pw.println("    service-permissions: dump permissions required by services");
20957                pw.println("    <package.name>: info about given package");
20958                return;
20959            } else if ("--checkin".equals(opt)) {
20960                checkin = true;
20961            } else if ("-f".equals(opt)) {
20962                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20963            } else if ("--proto".equals(opt)) {
20964                dumpProto(fd);
20965                return;
20966            } else {
20967                pw.println("Unknown argument: " + opt + "; use -h for help");
20968            }
20969        }
20970
20971        // Is the caller requesting to dump a particular piece of data?
20972        if (opti < args.length) {
20973            String cmd = args[opti];
20974            opti++;
20975            // Is this a package name?
20976            if ("android".equals(cmd) || cmd.contains(".")) {
20977                packageName = cmd;
20978                // When dumping a single package, we always dump all of its
20979                // filter information since the amount of data will be reasonable.
20980                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20981            } else if ("check-permission".equals(cmd)) {
20982                if (opti >= args.length) {
20983                    pw.println("Error: check-permission missing permission argument");
20984                    return;
20985                }
20986                String perm = args[opti];
20987                opti++;
20988                if (opti >= args.length) {
20989                    pw.println("Error: check-permission missing package argument");
20990                    return;
20991                }
20992
20993                String pkg = args[opti];
20994                opti++;
20995                int user = UserHandle.getUserId(Binder.getCallingUid());
20996                if (opti < args.length) {
20997                    try {
20998                        user = Integer.parseInt(args[opti]);
20999                    } catch (NumberFormatException e) {
21000                        pw.println("Error: check-permission user argument is not a number: "
21001                                + args[opti]);
21002                        return;
21003                    }
21004                }
21005
21006                // Normalize package name to handle renamed packages and static libs
21007                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21008
21009                pw.println(checkPermission(perm, pkg, user));
21010                return;
21011            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21012                dumpState.setDump(DumpState.DUMP_LIBS);
21013            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21014                dumpState.setDump(DumpState.DUMP_FEATURES);
21015            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21016                if (opti >= args.length) {
21017                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21018                            | DumpState.DUMP_SERVICE_RESOLVERS
21019                            | DumpState.DUMP_RECEIVER_RESOLVERS
21020                            | DumpState.DUMP_CONTENT_RESOLVERS);
21021                } else {
21022                    while (opti < args.length) {
21023                        String name = args[opti];
21024                        if ("a".equals(name) || "activity".equals(name)) {
21025                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21026                        } else if ("s".equals(name) || "service".equals(name)) {
21027                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21028                        } else if ("r".equals(name) || "receiver".equals(name)) {
21029                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21030                        } else if ("c".equals(name) || "content".equals(name)) {
21031                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21032                        } else {
21033                            pw.println("Error: unknown resolver table type: " + name);
21034                            return;
21035                        }
21036                        opti++;
21037                    }
21038                }
21039            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21040                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21041            } else if ("permission".equals(cmd)) {
21042                if (opti >= args.length) {
21043                    pw.println("Error: permission requires permission name");
21044                    return;
21045                }
21046                permissionNames = new ArraySet<>();
21047                while (opti < args.length) {
21048                    permissionNames.add(args[opti]);
21049                    opti++;
21050                }
21051                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21052                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21053            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21054                dumpState.setDump(DumpState.DUMP_PREFERRED);
21055            } else if ("preferred-xml".equals(cmd)) {
21056                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21057                if (opti < args.length && "--full".equals(args[opti])) {
21058                    fullPreferred = true;
21059                    opti++;
21060                }
21061            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21062                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21063            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21064                dumpState.setDump(DumpState.DUMP_PACKAGES);
21065            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21066                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21067            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21068                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21069            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21070                dumpState.setDump(DumpState.DUMP_MESSAGES);
21071            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21072                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21073            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21074                    || "intent-filter-verifiers".equals(cmd)) {
21075                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21076            } else if ("version".equals(cmd)) {
21077                dumpState.setDump(DumpState.DUMP_VERSION);
21078            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21079                dumpState.setDump(DumpState.DUMP_KEYSETS);
21080            } else if ("installs".equals(cmd)) {
21081                dumpState.setDump(DumpState.DUMP_INSTALLS);
21082            } else if ("frozen".equals(cmd)) {
21083                dumpState.setDump(DumpState.DUMP_FROZEN);
21084            } else if ("volumes".equals(cmd)) {
21085                dumpState.setDump(DumpState.DUMP_VOLUMES);
21086            } else if ("dexopt".equals(cmd)) {
21087                dumpState.setDump(DumpState.DUMP_DEXOPT);
21088            } else if ("compiler-stats".equals(cmd)) {
21089                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21090            } else if ("changes".equals(cmd)) {
21091                dumpState.setDump(DumpState.DUMP_CHANGES);
21092            } else if ("service-permissions".equals(cmd)) {
21093                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21094            } else if ("write".equals(cmd)) {
21095                synchronized (mPackages) {
21096                    mSettings.writeLPr();
21097                    pw.println("Settings written.");
21098                    return;
21099                }
21100            }
21101        }
21102
21103        if (checkin) {
21104            pw.println("vers,1");
21105        }
21106
21107        // reader
21108        synchronized (mPackages) {
21109            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21110                if (!checkin) {
21111                    if (dumpState.onTitlePrinted())
21112                        pw.println();
21113                    pw.println("Database versions:");
21114                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21115                }
21116            }
21117
21118            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21119                if (!checkin) {
21120                    if (dumpState.onTitlePrinted())
21121                        pw.println();
21122                    pw.println("Verifiers:");
21123                    pw.print("  Required: ");
21124                    pw.print(mRequiredVerifierPackage);
21125                    pw.print(" (uid=");
21126                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21127                            UserHandle.USER_SYSTEM));
21128                    pw.println(")");
21129                } else if (mRequiredVerifierPackage != null) {
21130                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21131                    pw.print(",");
21132                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21133                            UserHandle.USER_SYSTEM));
21134                }
21135            }
21136
21137            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21138                    packageName == null) {
21139                if (mIntentFilterVerifierComponent != null) {
21140                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21141                    if (!checkin) {
21142                        if (dumpState.onTitlePrinted())
21143                            pw.println();
21144                        pw.println("Intent Filter Verifier:");
21145                        pw.print("  Using: ");
21146                        pw.print(verifierPackageName);
21147                        pw.print(" (uid=");
21148                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21149                                UserHandle.USER_SYSTEM));
21150                        pw.println(")");
21151                    } else if (verifierPackageName != null) {
21152                        pw.print("ifv,"); pw.print(verifierPackageName);
21153                        pw.print(",");
21154                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21155                                UserHandle.USER_SYSTEM));
21156                    }
21157                } else {
21158                    pw.println();
21159                    pw.println("No Intent Filter Verifier available!");
21160                }
21161            }
21162
21163            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21164                boolean printedHeader = false;
21165                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21166                while (it.hasNext()) {
21167                    String libName = it.next();
21168                    LongSparseArray<SharedLibraryEntry> versionedLib
21169                            = mSharedLibraries.get(libName);
21170                    if (versionedLib == null) {
21171                        continue;
21172                    }
21173                    final int versionCount = versionedLib.size();
21174                    for (int i = 0; i < versionCount; i++) {
21175                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21176                        if (!checkin) {
21177                            if (!printedHeader) {
21178                                if (dumpState.onTitlePrinted())
21179                                    pw.println();
21180                                pw.println("Libraries:");
21181                                printedHeader = true;
21182                            }
21183                            pw.print("  ");
21184                        } else {
21185                            pw.print("lib,");
21186                        }
21187                        pw.print(libEntry.info.getName());
21188                        if (libEntry.info.isStatic()) {
21189                            pw.print(" version=" + libEntry.info.getLongVersion());
21190                        }
21191                        if (!checkin) {
21192                            pw.print(" -> ");
21193                        }
21194                        if (libEntry.path != null) {
21195                            pw.print(" (jar) ");
21196                            pw.print(libEntry.path);
21197                        } else {
21198                            pw.print(" (apk) ");
21199                            pw.print(libEntry.apk);
21200                        }
21201                        pw.println();
21202                    }
21203                }
21204            }
21205
21206            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21207                if (dumpState.onTitlePrinted())
21208                    pw.println();
21209                if (!checkin) {
21210                    pw.println("Features:");
21211                }
21212
21213                synchronized (mAvailableFeatures) {
21214                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21215                        if (checkin) {
21216                            pw.print("feat,");
21217                            pw.print(feat.name);
21218                            pw.print(",");
21219                            pw.println(feat.version);
21220                        } else {
21221                            pw.print("  ");
21222                            pw.print(feat.name);
21223                            if (feat.version > 0) {
21224                                pw.print(" version=");
21225                                pw.print(feat.version);
21226                            }
21227                            pw.println();
21228                        }
21229                    }
21230                }
21231            }
21232
21233            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21234                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21235                        : "Activity Resolver Table:", "  ", packageName,
21236                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21237                    dumpState.setTitlePrinted(true);
21238                }
21239            }
21240            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21241                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21242                        : "Receiver Resolver Table:", "  ", packageName,
21243                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21244                    dumpState.setTitlePrinted(true);
21245                }
21246            }
21247            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21248                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21249                        : "Service Resolver Table:", "  ", packageName,
21250                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21251                    dumpState.setTitlePrinted(true);
21252                }
21253            }
21254            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21255                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21256                        : "Provider Resolver Table:", "  ", packageName,
21257                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21258                    dumpState.setTitlePrinted(true);
21259                }
21260            }
21261
21262            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21263                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21264                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21265                    int user = mSettings.mPreferredActivities.keyAt(i);
21266                    if (pir.dump(pw,
21267                            dumpState.getTitlePrinted()
21268                                ? "\nPreferred Activities User " + user + ":"
21269                                : "Preferred Activities User " + user + ":", "  ",
21270                            packageName, true, false)) {
21271                        dumpState.setTitlePrinted(true);
21272                    }
21273                }
21274            }
21275
21276            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21277                pw.flush();
21278                FileOutputStream fout = new FileOutputStream(fd);
21279                BufferedOutputStream str = new BufferedOutputStream(fout);
21280                XmlSerializer serializer = new FastXmlSerializer();
21281                try {
21282                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21283                    serializer.startDocument(null, true);
21284                    serializer.setFeature(
21285                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21286                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21287                    serializer.endDocument();
21288                    serializer.flush();
21289                } catch (IllegalArgumentException e) {
21290                    pw.println("Failed writing: " + e);
21291                } catch (IllegalStateException e) {
21292                    pw.println("Failed writing: " + e);
21293                } catch (IOException e) {
21294                    pw.println("Failed writing: " + e);
21295                }
21296            }
21297
21298            if (!checkin
21299                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21300                    && packageName == null) {
21301                pw.println();
21302                int count = mSettings.mPackages.size();
21303                if (count == 0) {
21304                    pw.println("No applications!");
21305                    pw.println();
21306                } else {
21307                    final String prefix = "  ";
21308                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21309                    if (allPackageSettings.size() == 0) {
21310                        pw.println("No domain preferred apps!");
21311                        pw.println();
21312                    } else {
21313                        pw.println("App verification status:");
21314                        pw.println();
21315                        count = 0;
21316                        for (PackageSetting ps : allPackageSettings) {
21317                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21318                            if (ivi == null || ivi.getPackageName() == null) continue;
21319                            pw.println(prefix + "Package: " + ivi.getPackageName());
21320                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21321                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21322                            pw.println();
21323                            count++;
21324                        }
21325                        if (count == 0) {
21326                            pw.println(prefix + "No app verification established.");
21327                            pw.println();
21328                        }
21329                        for (int userId : sUserManager.getUserIds()) {
21330                            pw.println("App linkages for user " + userId + ":");
21331                            pw.println();
21332                            count = 0;
21333                            for (PackageSetting ps : allPackageSettings) {
21334                                final long status = ps.getDomainVerificationStatusForUser(userId);
21335                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21336                                        && !DEBUG_DOMAIN_VERIFICATION) {
21337                                    continue;
21338                                }
21339                                pw.println(prefix + "Package: " + ps.name);
21340                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21341                                String statusStr = IntentFilterVerificationInfo.
21342                                        getStatusStringFromValue(status);
21343                                pw.println(prefix + "Status:  " + statusStr);
21344                                pw.println();
21345                                count++;
21346                            }
21347                            if (count == 0) {
21348                                pw.println(prefix + "No configured app linkages.");
21349                                pw.println();
21350                            }
21351                        }
21352                    }
21353                }
21354            }
21355
21356            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21357                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21358            }
21359
21360            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21361                boolean printedSomething = false;
21362                for (PackageParser.Provider p : mProviders.mProviders.values()) {
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("Registered ContentProviders:");
21370                        printedSomething = true;
21371                    }
21372                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21373                    pw.print("    "); pw.println(p.toString());
21374                }
21375                printedSomething = false;
21376                for (Map.Entry<String, PackageParser.Provider> entry :
21377                        mProvidersByAuthority.entrySet()) {
21378                    PackageParser.Provider p = entry.getValue();
21379                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21380                        continue;
21381                    }
21382                    if (!printedSomething) {
21383                        if (dumpState.onTitlePrinted())
21384                            pw.println();
21385                        pw.println("ContentProvider Authorities:");
21386                        printedSomething = true;
21387                    }
21388                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21389                    pw.print("    "); pw.println(p.toString());
21390                    if (p.info != null && p.info.applicationInfo != null) {
21391                        final String appInfo = p.info.applicationInfo.toString();
21392                        pw.print("      applicationInfo="); pw.println(appInfo);
21393                    }
21394                }
21395            }
21396
21397            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21398                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21399            }
21400
21401            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21402                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21403            }
21404
21405            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21406                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21407            }
21408
21409            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21410                if (dumpState.onTitlePrinted()) pw.println();
21411                pw.println("Package Changes:");
21412                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21413                final int K = mChangedPackages.size();
21414                for (int i = 0; i < K; i++) {
21415                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21416                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21417                    final int N = changes.size();
21418                    if (N == 0) {
21419                        pw.print("    "); pw.println("No packages changed");
21420                    } else {
21421                        for (int j = 0; j < N; j++) {
21422                            final String pkgName = changes.valueAt(j);
21423                            final int sequenceNumber = changes.keyAt(j);
21424                            pw.print("    ");
21425                            pw.print("seq=");
21426                            pw.print(sequenceNumber);
21427                            pw.print(", package=");
21428                            pw.println(pkgName);
21429                        }
21430                    }
21431                }
21432            }
21433
21434            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21435                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21436            }
21437
21438            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21439                // XXX should handle packageName != null by dumping only install data that
21440                // the given package is involved with.
21441                if (dumpState.onTitlePrinted()) pw.println();
21442
21443                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21444                ipw.println();
21445                ipw.println("Frozen packages:");
21446                ipw.increaseIndent();
21447                if (mFrozenPackages.size() == 0) {
21448                    ipw.println("(none)");
21449                } else {
21450                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21451                        ipw.println(mFrozenPackages.valueAt(i));
21452                    }
21453                }
21454                ipw.decreaseIndent();
21455            }
21456
21457            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21458                if (dumpState.onTitlePrinted()) pw.println();
21459
21460                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21461                ipw.println();
21462                ipw.println("Loaded volumes:");
21463                ipw.increaseIndent();
21464                if (mLoadedVolumes.size() == 0) {
21465                    ipw.println("(none)");
21466                } else {
21467                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21468                        ipw.println(mLoadedVolumes.valueAt(i));
21469                    }
21470                }
21471                ipw.decreaseIndent();
21472            }
21473
21474            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21475                    && packageName == null) {
21476                if (dumpState.onTitlePrinted()) pw.println();
21477                pw.println("Service permissions:");
21478
21479                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21480                while (filterIterator.hasNext()) {
21481                    final ServiceIntentInfo info = filterIterator.next();
21482                    final ServiceInfo serviceInfo = info.service.info;
21483                    final String permission = serviceInfo.permission;
21484                    if (permission != null) {
21485                        pw.print("    ");
21486                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21487                        pw.print(": ");
21488                        pw.println(permission);
21489                    }
21490                }
21491            }
21492
21493            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21494                if (dumpState.onTitlePrinted()) pw.println();
21495                dumpDexoptStateLPr(pw, packageName);
21496            }
21497
21498            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21499                if (dumpState.onTitlePrinted()) pw.println();
21500                dumpCompilerStatsLPr(pw, packageName);
21501            }
21502
21503            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21504                if (dumpState.onTitlePrinted()) pw.println();
21505                mSettings.dumpReadMessagesLPr(pw, dumpState);
21506
21507                pw.println();
21508                pw.println("Package warning messages:");
21509                dumpCriticalInfo(pw, null);
21510            }
21511
21512            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21513                dumpCriticalInfo(pw, "msg,");
21514            }
21515        }
21516
21517        // PackageInstaller should be called outside of mPackages lock
21518        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21519            // XXX should handle packageName != null by dumping only install data that
21520            // the given package is involved with.
21521            if (dumpState.onTitlePrinted()) pw.println();
21522            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21523        }
21524    }
21525
21526    private void dumpProto(FileDescriptor fd) {
21527        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21528
21529        synchronized (mPackages) {
21530            final long requiredVerifierPackageToken =
21531                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21532            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21533            proto.write(
21534                    PackageServiceDumpProto.PackageShortProto.UID,
21535                    getPackageUid(
21536                            mRequiredVerifierPackage,
21537                            MATCH_DEBUG_TRIAGED_MISSING,
21538                            UserHandle.USER_SYSTEM));
21539            proto.end(requiredVerifierPackageToken);
21540
21541            if (mIntentFilterVerifierComponent != null) {
21542                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21543                final long verifierPackageToken =
21544                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21545                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21546                proto.write(
21547                        PackageServiceDumpProto.PackageShortProto.UID,
21548                        getPackageUid(
21549                                verifierPackageName,
21550                                MATCH_DEBUG_TRIAGED_MISSING,
21551                                UserHandle.USER_SYSTEM));
21552                proto.end(verifierPackageToken);
21553            }
21554
21555            dumpSharedLibrariesProto(proto);
21556            dumpFeaturesProto(proto);
21557            mSettings.dumpPackagesProto(proto);
21558            mSettings.dumpSharedUsersProto(proto);
21559            dumpCriticalInfo(proto);
21560        }
21561        proto.flush();
21562    }
21563
21564    private void dumpFeaturesProto(ProtoOutputStream proto) {
21565        synchronized (mAvailableFeatures) {
21566            final int count = mAvailableFeatures.size();
21567            for (int i = 0; i < count; i++) {
21568                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21569            }
21570        }
21571    }
21572
21573    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21574        final int count = mSharedLibraries.size();
21575        for (int i = 0; i < count; i++) {
21576            final String libName = mSharedLibraries.keyAt(i);
21577            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21578            if (versionedLib == null) {
21579                continue;
21580            }
21581            final int versionCount = versionedLib.size();
21582            for (int j = 0; j < versionCount; j++) {
21583                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21584                final long sharedLibraryToken =
21585                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21586                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21587                final boolean isJar = (libEntry.path != null);
21588                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21589                if (isJar) {
21590                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21591                } else {
21592                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21593                }
21594                proto.end(sharedLibraryToken);
21595            }
21596        }
21597    }
21598
21599    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21600        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21601        ipw.println();
21602        ipw.println("Dexopt state:");
21603        ipw.increaseIndent();
21604        Collection<PackageParser.Package> packages = null;
21605        if (packageName != null) {
21606            PackageParser.Package targetPackage = mPackages.get(packageName);
21607            if (targetPackage != null) {
21608                packages = Collections.singletonList(targetPackage);
21609            } else {
21610                ipw.println("Unable to find package: " + packageName);
21611                return;
21612            }
21613        } else {
21614            packages = mPackages.values();
21615        }
21616
21617        for (PackageParser.Package pkg : packages) {
21618            ipw.println("[" + pkg.packageName + "]");
21619            ipw.increaseIndent();
21620            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21621                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21622            ipw.decreaseIndent();
21623        }
21624    }
21625
21626    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21627        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21628        ipw.println();
21629        ipw.println("Compiler stats:");
21630        ipw.increaseIndent();
21631        Collection<PackageParser.Package> packages = null;
21632        if (packageName != null) {
21633            PackageParser.Package targetPackage = mPackages.get(packageName);
21634            if (targetPackage != null) {
21635                packages = Collections.singletonList(targetPackage);
21636            } else {
21637                ipw.println("Unable to find package: " + packageName);
21638                return;
21639            }
21640        } else {
21641            packages = mPackages.values();
21642        }
21643
21644        for (PackageParser.Package pkg : packages) {
21645            ipw.println("[" + pkg.packageName + "]");
21646            ipw.increaseIndent();
21647
21648            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21649            if (stats == null) {
21650                ipw.println("(No recorded stats)");
21651            } else {
21652                stats.dump(ipw);
21653            }
21654            ipw.decreaseIndent();
21655        }
21656    }
21657
21658    private String dumpDomainString(String packageName) {
21659        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21660                .getList();
21661        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21662
21663        ArraySet<String> result = new ArraySet<>();
21664        if (iviList.size() > 0) {
21665            for (IntentFilterVerificationInfo ivi : iviList) {
21666                for (String host : ivi.getDomains()) {
21667                    result.add(host);
21668                }
21669            }
21670        }
21671        if (filters != null && filters.size() > 0) {
21672            for (IntentFilter filter : filters) {
21673                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21674                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21675                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21676                    result.addAll(filter.getHostsList());
21677                }
21678            }
21679        }
21680
21681        StringBuilder sb = new StringBuilder(result.size() * 16);
21682        for (String domain : result) {
21683            if (sb.length() > 0) sb.append(" ");
21684            sb.append(domain);
21685        }
21686        return sb.toString();
21687    }
21688
21689    // ------- apps on sdcard specific code -------
21690    static final boolean DEBUG_SD_INSTALL = false;
21691
21692    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21693
21694    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21695
21696    private boolean mMediaMounted = false;
21697
21698    static String getEncryptKey() {
21699        try {
21700            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21701                    SD_ENCRYPTION_KEYSTORE_NAME);
21702            if (sdEncKey == null) {
21703                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21704                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21705                if (sdEncKey == null) {
21706                    Slog.e(TAG, "Failed to create encryption keys");
21707                    return null;
21708                }
21709            }
21710            return sdEncKey;
21711        } catch (NoSuchAlgorithmException nsae) {
21712            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21713            return null;
21714        } catch (IOException ioe) {
21715            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21716            return null;
21717        }
21718    }
21719
21720    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21721            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21722        final int size = infos.size();
21723        final String[] packageNames = new String[size];
21724        final int[] packageUids = new int[size];
21725        for (int i = 0; i < size; i++) {
21726            final ApplicationInfo info = infos.get(i);
21727            packageNames[i] = info.packageName;
21728            packageUids[i] = info.uid;
21729        }
21730        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21731                finishedReceiver);
21732    }
21733
21734    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21735            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21736        sendResourcesChangedBroadcast(mediaStatus, replacing,
21737                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21738    }
21739
21740    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21741            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21742        int size = pkgList.length;
21743        if (size > 0) {
21744            // Send broadcasts here
21745            Bundle extras = new Bundle();
21746            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21747            if (uidArr != null) {
21748                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21749            }
21750            if (replacing) {
21751                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21752            }
21753            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21754                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21755            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21756        }
21757    }
21758
21759    private void loadPrivatePackages(final VolumeInfo vol) {
21760        mHandler.post(new Runnable() {
21761            @Override
21762            public void run() {
21763                loadPrivatePackagesInner(vol);
21764            }
21765        });
21766    }
21767
21768    private void loadPrivatePackagesInner(VolumeInfo vol) {
21769        final String volumeUuid = vol.fsUuid;
21770        if (TextUtils.isEmpty(volumeUuid)) {
21771            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21772            return;
21773        }
21774
21775        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21776        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21777        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21778
21779        final VersionInfo ver;
21780        final List<PackageSetting> packages;
21781        synchronized (mPackages) {
21782            ver = mSettings.findOrCreateVersion(volumeUuid);
21783            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21784        }
21785
21786        for (PackageSetting ps : packages) {
21787            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21788            synchronized (mInstallLock) {
21789                final PackageParser.Package pkg;
21790                try {
21791                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21792                    loaded.add(pkg.applicationInfo);
21793
21794                } catch (PackageManagerException e) {
21795                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21796                }
21797
21798                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21799                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21800                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21801                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21802                }
21803            }
21804        }
21805
21806        // Reconcile app data for all started/unlocked users
21807        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21808        final UserManager um = mContext.getSystemService(UserManager.class);
21809        UserManagerInternal umInternal = getUserManagerInternal();
21810        for (UserInfo user : um.getUsers()) {
21811            final int flags;
21812            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21813                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21814            } else if (umInternal.isUserRunning(user.id)) {
21815                flags = StorageManager.FLAG_STORAGE_DE;
21816            } else {
21817                continue;
21818            }
21819
21820            try {
21821                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21822                synchronized (mInstallLock) {
21823                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21824                }
21825            } catch (IllegalStateException e) {
21826                // Device was probably ejected, and we'll process that event momentarily
21827                Slog.w(TAG, "Failed to prepare storage: " + e);
21828            }
21829        }
21830
21831        synchronized (mPackages) {
21832            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21833            if (sdkUpdated) {
21834                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21835                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21836            }
21837            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21838                    mPermissionCallback);
21839
21840            // Yay, everything is now upgraded
21841            ver.forceCurrent();
21842
21843            mSettings.writeLPr();
21844        }
21845
21846        for (PackageFreezer freezer : freezers) {
21847            freezer.close();
21848        }
21849
21850        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21851        sendResourcesChangedBroadcast(true, false, loaded, null);
21852        mLoadedVolumes.add(vol.getId());
21853    }
21854
21855    private void unloadPrivatePackages(final VolumeInfo vol) {
21856        mHandler.post(new Runnable() {
21857            @Override
21858            public void run() {
21859                unloadPrivatePackagesInner(vol);
21860            }
21861        });
21862    }
21863
21864    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21865        final String volumeUuid = vol.fsUuid;
21866        if (TextUtils.isEmpty(volumeUuid)) {
21867            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21868            return;
21869        }
21870
21871        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21872        synchronized (mInstallLock) {
21873        synchronized (mPackages) {
21874            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21875            for (PackageSetting ps : packages) {
21876                if (ps.pkg == null) continue;
21877
21878                final ApplicationInfo info = ps.pkg.applicationInfo;
21879                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21880                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21881
21882                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21883                        "unloadPrivatePackagesInner")) {
21884                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21885                            false, null)) {
21886                        unloaded.add(info);
21887                    } else {
21888                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21889                    }
21890                }
21891
21892                // Try very hard to release any references to this package
21893                // so we don't risk the system server being killed due to
21894                // open FDs
21895                AttributeCache.instance().removePackage(ps.name);
21896            }
21897
21898            mSettings.writeLPr();
21899        }
21900        }
21901
21902        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21903        sendResourcesChangedBroadcast(false, false, unloaded, null);
21904        mLoadedVolumes.remove(vol.getId());
21905
21906        // Try very hard to release any references to this path so we don't risk
21907        // the system server being killed due to open FDs
21908        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21909
21910        for (int i = 0; i < 3; i++) {
21911            System.gc();
21912            System.runFinalization();
21913        }
21914    }
21915
21916    private void assertPackageKnown(String volumeUuid, String packageName)
21917            throws PackageManagerException {
21918        synchronized (mPackages) {
21919            // Normalize package name to handle renamed packages
21920            packageName = normalizePackageNameLPr(packageName);
21921
21922            final PackageSetting ps = mSettings.mPackages.get(packageName);
21923            if (ps == null) {
21924                throw new PackageManagerException("Package " + packageName + " is unknown");
21925            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21926                throw new PackageManagerException(
21927                        "Package " + packageName + " found on unknown volume " + volumeUuid
21928                                + "; expected volume " + ps.volumeUuid);
21929            }
21930        }
21931    }
21932
21933    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21934            throws PackageManagerException {
21935        synchronized (mPackages) {
21936            // Normalize package name to handle renamed packages
21937            packageName = normalizePackageNameLPr(packageName);
21938
21939            final PackageSetting ps = mSettings.mPackages.get(packageName);
21940            if (ps == null) {
21941                throw new PackageManagerException("Package " + packageName + " is unknown");
21942            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21943                throw new PackageManagerException(
21944                        "Package " + packageName + " found on unknown volume " + volumeUuid
21945                                + "; expected volume " + ps.volumeUuid);
21946            } else if (!ps.getInstalled(userId)) {
21947                throw new PackageManagerException(
21948                        "Package " + packageName + " not installed for user " + userId);
21949            }
21950        }
21951    }
21952
21953    private List<String> collectAbsoluteCodePaths() {
21954        synchronized (mPackages) {
21955            List<String> codePaths = new ArrayList<>();
21956            final int packageCount = mSettings.mPackages.size();
21957            for (int i = 0; i < packageCount; i++) {
21958                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21959                codePaths.add(ps.codePath.getAbsolutePath());
21960            }
21961            return codePaths;
21962        }
21963    }
21964
21965    /**
21966     * Examine all apps present on given mounted volume, and destroy apps that
21967     * aren't expected, either due to uninstallation or reinstallation on
21968     * another volume.
21969     */
21970    private void reconcileApps(String volumeUuid) {
21971        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21972        List<File> filesToDelete = null;
21973
21974        final File[] files = FileUtils.listFilesOrEmpty(
21975                Environment.getDataAppDirectory(volumeUuid));
21976        for (File file : files) {
21977            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21978                    && !PackageInstallerService.isStageName(file.getName());
21979            if (!isPackage) {
21980                // Ignore entries which are not packages
21981                continue;
21982            }
21983
21984            String absolutePath = file.getAbsolutePath();
21985
21986            boolean pathValid = false;
21987            final int absoluteCodePathCount = absoluteCodePaths.size();
21988            for (int i = 0; i < absoluteCodePathCount; i++) {
21989                String absoluteCodePath = absoluteCodePaths.get(i);
21990                if (absolutePath.startsWith(absoluteCodePath)) {
21991                    pathValid = true;
21992                    break;
21993                }
21994            }
21995
21996            if (!pathValid) {
21997                if (filesToDelete == null) {
21998                    filesToDelete = new ArrayList<>();
21999                }
22000                filesToDelete.add(file);
22001            }
22002        }
22003
22004        if (filesToDelete != null) {
22005            final int fileToDeleteCount = filesToDelete.size();
22006            for (int i = 0; i < fileToDeleteCount; i++) {
22007                File fileToDelete = filesToDelete.get(i);
22008                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22009                synchronized (mInstallLock) {
22010                    removeCodePathLI(fileToDelete);
22011                }
22012            }
22013        }
22014    }
22015
22016    /**
22017     * Reconcile all app data for the given user.
22018     * <p>
22019     * Verifies that directories exist and that ownership and labeling is
22020     * correct for all installed apps on all mounted volumes.
22021     */
22022    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22023        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22024        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22025            final String volumeUuid = vol.getFsUuid();
22026            synchronized (mInstallLock) {
22027                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22028            }
22029        }
22030    }
22031
22032    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22033            boolean migrateAppData) {
22034        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22035    }
22036
22037    /**
22038     * Reconcile all app data on given mounted volume.
22039     * <p>
22040     * Destroys app data that isn't expected, either due to uninstallation or
22041     * reinstallation on another volume.
22042     * <p>
22043     * Verifies that directories exist and that ownership and labeling is
22044     * correct for all installed apps.
22045     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22046     */
22047    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22048            boolean migrateAppData, boolean onlyCoreApps) {
22049        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22050                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22051        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22052
22053        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22054        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22055
22056        // First look for stale data that doesn't belong, and check if things
22057        // have changed since we did our last restorecon
22058        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22059            if (StorageManager.isFileEncryptedNativeOrEmulated()
22060                    && !StorageManager.isUserKeyUnlocked(userId)) {
22061                throw new RuntimeException(
22062                        "Yikes, someone asked us to reconcile CE storage while " + userId
22063                                + " was still locked; this would have caused massive data loss!");
22064            }
22065
22066            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22067            for (File file : files) {
22068                final String packageName = file.getName();
22069                try {
22070                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22071                } catch (PackageManagerException e) {
22072                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22073                    try {
22074                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22075                                StorageManager.FLAG_STORAGE_CE, 0);
22076                    } catch (InstallerException e2) {
22077                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22078                    }
22079                }
22080            }
22081        }
22082        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22083            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22084            for (File file : files) {
22085                final String packageName = file.getName();
22086                try {
22087                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22088                } catch (PackageManagerException e) {
22089                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22090                    try {
22091                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22092                                StorageManager.FLAG_STORAGE_DE, 0);
22093                    } catch (InstallerException e2) {
22094                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22095                    }
22096                }
22097            }
22098        }
22099
22100        // Ensure that data directories are ready to roll for all packages
22101        // installed for this volume and user
22102        final List<PackageSetting> packages;
22103        synchronized (mPackages) {
22104            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22105        }
22106        int preparedCount = 0;
22107        for (PackageSetting ps : packages) {
22108            final String packageName = ps.name;
22109            if (ps.pkg == null) {
22110                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22111                // TODO: might be due to legacy ASEC apps; we should circle back
22112                // and reconcile again once they're scanned
22113                continue;
22114            }
22115            // Skip non-core apps if requested
22116            if (onlyCoreApps && !ps.pkg.coreApp) {
22117                result.add(packageName);
22118                continue;
22119            }
22120
22121            if (ps.getInstalled(userId)) {
22122                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22123                preparedCount++;
22124            }
22125        }
22126
22127        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22128        return result;
22129    }
22130
22131    /**
22132     * Prepare app data for the given app just after it was installed or
22133     * upgraded. This method carefully only touches users that it's installed
22134     * for, and it forces a restorecon to handle any seinfo changes.
22135     * <p>
22136     * Verifies that directories exist and that ownership and labeling is
22137     * correct for all installed apps. If there is an ownership mismatch, it
22138     * will try recovering system apps by wiping data; third-party app data is
22139     * left intact.
22140     * <p>
22141     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22142     */
22143    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22144        final PackageSetting ps;
22145        synchronized (mPackages) {
22146            ps = mSettings.mPackages.get(pkg.packageName);
22147            mSettings.writeKernelMappingLPr(ps);
22148        }
22149
22150        final UserManager um = mContext.getSystemService(UserManager.class);
22151        UserManagerInternal umInternal = getUserManagerInternal();
22152        for (UserInfo user : um.getUsers()) {
22153            final int flags;
22154            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22155                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22156            } else if (umInternal.isUserRunning(user.id)) {
22157                flags = StorageManager.FLAG_STORAGE_DE;
22158            } else {
22159                continue;
22160            }
22161
22162            if (ps.getInstalled(user.id)) {
22163                // TODO: when user data is locked, mark that we're still dirty
22164                prepareAppDataLIF(pkg, user.id, flags);
22165            }
22166        }
22167    }
22168
22169    /**
22170     * Prepare app data for the given app.
22171     * <p>
22172     * Verifies that directories exist and that ownership and labeling is
22173     * correct for all installed apps. If there is an ownership mismatch, this
22174     * will try recovering system apps by wiping data; third-party app data is
22175     * left intact.
22176     */
22177    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22178        if (pkg == null) {
22179            Slog.wtf(TAG, "Package was null!", new Throwable());
22180            return;
22181        }
22182        prepareAppDataLeafLIF(pkg, userId, flags);
22183        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22184        for (int i = 0; i < childCount; i++) {
22185            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22186        }
22187    }
22188
22189    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22190            boolean maybeMigrateAppData) {
22191        prepareAppDataLIF(pkg, userId, flags);
22192
22193        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22194            // We may have just shuffled around app data directories, so
22195            // prepare them one more time
22196            prepareAppDataLIF(pkg, userId, flags);
22197        }
22198    }
22199
22200    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22201        if (DEBUG_APP_DATA) {
22202            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22203                    + Integer.toHexString(flags));
22204        }
22205
22206        final String volumeUuid = pkg.volumeUuid;
22207        final String packageName = pkg.packageName;
22208        final ApplicationInfo app = pkg.applicationInfo;
22209        final int appId = UserHandle.getAppId(app.uid);
22210
22211        Preconditions.checkNotNull(app.seInfo);
22212
22213        long ceDataInode = -1;
22214        try {
22215            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22216                    appId, app.seInfo, app.targetSdkVersion);
22217        } catch (InstallerException e) {
22218            if (app.isSystemApp()) {
22219                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22220                        + ", but trying to recover: " + e);
22221                destroyAppDataLeafLIF(pkg, userId, flags);
22222                try {
22223                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22224                            appId, app.seInfo, app.targetSdkVersion);
22225                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22226                } catch (InstallerException e2) {
22227                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22228                }
22229            } else {
22230                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22231            }
22232        }
22233        // Prepare the application profiles.
22234        mArtManagerService.prepareAppProfiles(pkg, userId);
22235
22236        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22237            // TODO: mark this structure as dirty so we persist it!
22238            synchronized (mPackages) {
22239                final PackageSetting ps = mSettings.mPackages.get(packageName);
22240                if (ps != null) {
22241                    ps.setCeDataInode(ceDataInode, userId);
22242                }
22243            }
22244        }
22245
22246        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22247    }
22248
22249    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22250        if (pkg == null) {
22251            Slog.wtf(TAG, "Package was null!", new Throwable());
22252            return;
22253        }
22254        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22255        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22256        for (int i = 0; i < childCount; i++) {
22257            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22258        }
22259    }
22260
22261    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22262        final String volumeUuid = pkg.volumeUuid;
22263        final String packageName = pkg.packageName;
22264        final ApplicationInfo app = pkg.applicationInfo;
22265
22266        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22267            // Create a native library symlink only if we have native libraries
22268            // and if the native libraries are 32 bit libraries. We do not provide
22269            // this symlink for 64 bit libraries.
22270            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22271                final String nativeLibPath = app.nativeLibraryDir;
22272                try {
22273                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22274                            nativeLibPath, userId);
22275                } catch (InstallerException e) {
22276                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22277                }
22278            }
22279        }
22280    }
22281
22282    /**
22283     * For system apps on non-FBE devices, this method migrates any existing
22284     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22285     * requested by the app.
22286     */
22287    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22288        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22289                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22290            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22291                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22292            try {
22293                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22294                        storageTarget);
22295            } catch (InstallerException e) {
22296                logCriticalInfo(Log.WARN,
22297                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22298            }
22299            return true;
22300        } else {
22301            return false;
22302        }
22303    }
22304
22305    public PackageFreezer freezePackage(String packageName, String killReason) {
22306        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22307    }
22308
22309    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22310        return new PackageFreezer(packageName, userId, killReason);
22311    }
22312
22313    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22314            String killReason) {
22315        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22316    }
22317
22318    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22319            String killReason) {
22320        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22321            return new PackageFreezer();
22322        } else {
22323            return freezePackage(packageName, userId, killReason);
22324        }
22325    }
22326
22327    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22328            String killReason) {
22329        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22330    }
22331
22332    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22333            String killReason) {
22334        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22335            return new PackageFreezer();
22336        } else {
22337            return freezePackage(packageName, userId, killReason);
22338        }
22339    }
22340
22341    /**
22342     * Class that freezes and kills the given package upon creation, and
22343     * unfreezes it upon closing. This is typically used when doing surgery on
22344     * app code/data to prevent the app from running while you're working.
22345     */
22346    private class PackageFreezer implements AutoCloseable {
22347        private final String mPackageName;
22348        private final PackageFreezer[] mChildren;
22349
22350        private final boolean mWeFroze;
22351
22352        private final AtomicBoolean mClosed = new AtomicBoolean();
22353        private final CloseGuard mCloseGuard = CloseGuard.get();
22354
22355        /**
22356         * Create and return a stub freezer that doesn't actually do anything,
22357         * typically used when someone requested
22358         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22359         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22360         */
22361        public PackageFreezer() {
22362            mPackageName = null;
22363            mChildren = null;
22364            mWeFroze = false;
22365            mCloseGuard.open("close");
22366        }
22367
22368        public PackageFreezer(String packageName, int userId, String killReason) {
22369            synchronized (mPackages) {
22370                mPackageName = packageName;
22371                mWeFroze = mFrozenPackages.add(mPackageName);
22372
22373                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22374                if (ps != null) {
22375                    killApplication(ps.name, ps.appId, userId, killReason);
22376                }
22377
22378                final PackageParser.Package p = mPackages.get(packageName);
22379                if (p != null && p.childPackages != null) {
22380                    final int N = p.childPackages.size();
22381                    mChildren = new PackageFreezer[N];
22382                    for (int i = 0; i < N; i++) {
22383                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22384                                userId, killReason);
22385                    }
22386                } else {
22387                    mChildren = null;
22388                }
22389            }
22390            mCloseGuard.open("close");
22391        }
22392
22393        @Override
22394        protected void finalize() throws Throwable {
22395            try {
22396                if (mCloseGuard != null) {
22397                    mCloseGuard.warnIfOpen();
22398                }
22399
22400                close();
22401            } finally {
22402                super.finalize();
22403            }
22404        }
22405
22406        @Override
22407        public void close() {
22408            mCloseGuard.close();
22409            if (mClosed.compareAndSet(false, true)) {
22410                synchronized (mPackages) {
22411                    if (mWeFroze) {
22412                        mFrozenPackages.remove(mPackageName);
22413                    }
22414
22415                    if (mChildren != null) {
22416                        for (PackageFreezer freezer : mChildren) {
22417                            freezer.close();
22418                        }
22419                    }
22420                }
22421            }
22422        }
22423    }
22424
22425    /**
22426     * Verify that given package is currently frozen.
22427     */
22428    private void checkPackageFrozen(String packageName) {
22429        synchronized (mPackages) {
22430            if (!mFrozenPackages.contains(packageName)) {
22431                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22432            }
22433        }
22434    }
22435
22436    @Override
22437    public int movePackage(final String packageName, final String volumeUuid) {
22438        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22439
22440        final int callingUid = Binder.getCallingUid();
22441        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22442        final int moveId = mNextMoveId.getAndIncrement();
22443        mHandler.post(new Runnable() {
22444            @Override
22445            public void run() {
22446                try {
22447                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22448                } catch (PackageManagerException e) {
22449                    Slog.w(TAG, "Failed to move " + packageName, e);
22450                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22451                }
22452            }
22453        });
22454        return moveId;
22455    }
22456
22457    private void movePackageInternal(final String packageName, final String volumeUuid,
22458            final int moveId, final int callingUid, UserHandle user)
22459                    throws PackageManagerException {
22460        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22461        final PackageManager pm = mContext.getPackageManager();
22462
22463        final boolean currentAsec;
22464        final String currentVolumeUuid;
22465        final File codeFile;
22466        final String installerPackageName;
22467        final String packageAbiOverride;
22468        final int appId;
22469        final String seinfo;
22470        final String label;
22471        final int targetSdkVersion;
22472        final PackageFreezer freezer;
22473        final int[] installedUserIds;
22474
22475        // reader
22476        synchronized (mPackages) {
22477            final PackageParser.Package pkg = mPackages.get(packageName);
22478            final PackageSetting ps = mSettings.mPackages.get(packageName);
22479            if (pkg == null
22480                    || ps == null
22481                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22482                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22483            }
22484            if (pkg.applicationInfo.isSystemApp()) {
22485                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22486                        "Cannot move system application");
22487            }
22488
22489            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22490            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22491                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22492            if (isInternalStorage && !allow3rdPartyOnInternal) {
22493                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22494                        "3rd party apps are not allowed on internal storage");
22495            }
22496
22497            if (pkg.applicationInfo.isExternalAsec()) {
22498                currentAsec = true;
22499                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22500            } else if (pkg.applicationInfo.isForwardLocked()) {
22501                currentAsec = true;
22502                currentVolumeUuid = "forward_locked";
22503            } else {
22504                currentAsec = false;
22505                currentVolumeUuid = ps.volumeUuid;
22506
22507                final File probe = new File(pkg.codePath);
22508                final File probeOat = new File(probe, "oat");
22509                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22510                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22511                            "Move only supported for modern cluster style installs");
22512                }
22513            }
22514
22515            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22516                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22517                        "Package already moved to " + volumeUuid);
22518            }
22519            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22520                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22521                        "Device admin cannot be moved");
22522            }
22523
22524            if (mFrozenPackages.contains(packageName)) {
22525                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22526                        "Failed to move already frozen package");
22527            }
22528
22529            codeFile = new File(pkg.codePath);
22530            installerPackageName = ps.installerPackageName;
22531            packageAbiOverride = ps.cpuAbiOverrideString;
22532            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22533            seinfo = pkg.applicationInfo.seInfo;
22534            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22535            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22536            freezer = freezePackage(packageName, "movePackageInternal");
22537            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22538        }
22539
22540        final Bundle extras = new Bundle();
22541        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22542        extras.putString(Intent.EXTRA_TITLE, label);
22543        mMoveCallbacks.notifyCreated(moveId, extras);
22544
22545        int installFlags;
22546        final boolean moveCompleteApp;
22547        final File measurePath;
22548
22549        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22550            installFlags = INSTALL_INTERNAL;
22551            moveCompleteApp = !currentAsec;
22552            measurePath = Environment.getDataAppDirectory(volumeUuid);
22553        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22554            installFlags = INSTALL_EXTERNAL;
22555            moveCompleteApp = false;
22556            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22557        } else {
22558            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22559            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22560                    || !volume.isMountedWritable()) {
22561                freezer.close();
22562                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22563                        "Move location not mounted private volume");
22564            }
22565
22566            Preconditions.checkState(!currentAsec);
22567
22568            installFlags = INSTALL_INTERNAL;
22569            moveCompleteApp = true;
22570            measurePath = Environment.getDataAppDirectory(volumeUuid);
22571        }
22572
22573        // If we're moving app data around, we need all the users unlocked
22574        if (moveCompleteApp) {
22575            for (int userId : installedUserIds) {
22576                if (StorageManager.isFileEncryptedNativeOrEmulated()
22577                        && !StorageManager.isUserKeyUnlocked(userId)) {
22578                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22579                            "User " + userId + " must be unlocked");
22580                }
22581            }
22582        }
22583
22584        final PackageStats stats = new PackageStats(null, -1);
22585        synchronized (mInstaller) {
22586            for (int userId : installedUserIds) {
22587                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22588                    freezer.close();
22589                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22590                            "Failed to measure package size");
22591                }
22592            }
22593        }
22594
22595        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22596                + stats.dataSize);
22597
22598        final long startFreeBytes = measurePath.getUsableSpace();
22599        final long sizeBytes;
22600        if (moveCompleteApp) {
22601            sizeBytes = stats.codeSize + stats.dataSize;
22602        } else {
22603            sizeBytes = stats.codeSize;
22604        }
22605
22606        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22607            freezer.close();
22608            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22609                    "Not enough free space to move");
22610        }
22611
22612        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22613
22614        final CountDownLatch installedLatch = new CountDownLatch(1);
22615        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22616            @Override
22617            public void onUserActionRequired(Intent intent) throws RemoteException {
22618                throw new IllegalStateException();
22619            }
22620
22621            @Override
22622            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22623                    Bundle extras) throws RemoteException {
22624                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22625                        + PackageManager.installStatusToString(returnCode, msg));
22626
22627                installedLatch.countDown();
22628                freezer.close();
22629
22630                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22631                switch (status) {
22632                    case PackageInstaller.STATUS_SUCCESS:
22633                        mMoveCallbacks.notifyStatusChanged(moveId,
22634                                PackageManager.MOVE_SUCCEEDED);
22635                        break;
22636                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22637                        mMoveCallbacks.notifyStatusChanged(moveId,
22638                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22639                        break;
22640                    default:
22641                        mMoveCallbacks.notifyStatusChanged(moveId,
22642                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22643                        break;
22644                }
22645            }
22646        };
22647
22648        final MoveInfo move;
22649        if (moveCompleteApp) {
22650            // Kick off a thread to report progress estimates
22651            new Thread() {
22652                @Override
22653                public void run() {
22654                    while (true) {
22655                        try {
22656                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22657                                break;
22658                            }
22659                        } catch (InterruptedException ignored) {
22660                        }
22661
22662                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22663                        final int progress = 10 + (int) MathUtils.constrain(
22664                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22665                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22666                    }
22667                }
22668            }.start();
22669
22670            final String dataAppName = codeFile.getName();
22671            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22672                    dataAppName, appId, seinfo, targetSdkVersion);
22673        } else {
22674            move = null;
22675        }
22676
22677        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22678
22679        final Message msg = mHandler.obtainMessage(INIT_COPY);
22680        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22681        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22682                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22683                packageAbiOverride, null /*grantedPermissions*/,
22684                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22685        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22686        msg.obj = params;
22687
22688        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22689                System.identityHashCode(msg.obj));
22690        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22691                System.identityHashCode(msg.obj));
22692
22693        mHandler.sendMessage(msg);
22694    }
22695
22696    @Override
22697    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22698        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22699
22700        final int realMoveId = mNextMoveId.getAndIncrement();
22701        final Bundle extras = new Bundle();
22702        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22703        mMoveCallbacks.notifyCreated(realMoveId, extras);
22704
22705        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22706            @Override
22707            public void onCreated(int moveId, Bundle extras) {
22708                // Ignored
22709            }
22710
22711            @Override
22712            public void onStatusChanged(int moveId, int status, long estMillis) {
22713                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22714            }
22715        };
22716
22717        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22718        storage.setPrimaryStorageUuid(volumeUuid, callback);
22719        return realMoveId;
22720    }
22721
22722    @Override
22723    public int getMoveStatus(int moveId) {
22724        mContext.enforceCallingOrSelfPermission(
22725                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22726        return mMoveCallbacks.mLastStatus.get(moveId);
22727    }
22728
22729    @Override
22730    public void registerMoveCallback(IPackageMoveObserver callback) {
22731        mContext.enforceCallingOrSelfPermission(
22732                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22733        mMoveCallbacks.register(callback);
22734    }
22735
22736    @Override
22737    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22738        mContext.enforceCallingOrSelfPermission(
22739                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22740        mMoveCallbacks.unregister(callback);
22741    }
22742
22743    @Override
22744    public boolean setInstallLocation(int loc) {
22745        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22746                null);
22747        if (getInstallLocation() == loc) {
22748            return true;
22749        }
22750        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22751                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22752            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22753                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22754            return true;
22755        }
22756        return false;
22757   }
22758
22759    @Override
22760    public int getInstallLocation() {
22761        // allow instant app access
22762        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22763                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22764                PackageHelper.APP_INSTALL_AUTO);
22765    }
22766
22767    /** Called by UserManagerService */
22768    void cleanUpUser(UserManagerService userManager, int userHandle) {
22769        synchronized (mPackages) {
22770            mDirtyUsers.remove(userHandle);
22771            mUserNeedsBadging.delete(userHandle);
22772            mSettings.removeUserLPw(userHandle);
22773            mPendingBroadcasts.remove(userHandle);
22774            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22775            removeUnusedPackagesLPw(userManager, userHandle);
22776        }
22777    }
22778
22779    /**
22780     * We're removing userHandle and would like to remove any downloaded packages
22781     * that are no longer in use by any other user.
22782     * @param userHandle the user being removed
22783     */
22784    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22785        final boolean DEBUG_CLEAN_APKS = false;
22786        int [] users = userManager.getUserIds();
22787        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22788        while (psit.hasNext()) {
22789            PackageSetting ps = psit.next();
22790            if (ps.pkg == null) {
22791                continue;
22792            }
22793            final String packageName = ps.pkg.packageName;
22794            // Skip over if system app
22795            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22796                continue;
22797            }
22798            if (DEBUG_CLEAN_APKS) {
22799                Slog.i(TAG, "Checking package " + packageName);
22800            }
22801            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22802            if (keep) {
22803                if (DEBUG_CLEAN_APKS) {
22804                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22805                }
22806            } else {
22807                for (int i = 0; i < users.length; i++) {
22808                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22809                        keep = true;
22810                        if (DEBUG_CLEAN_APKS) {
22811                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22812                                    + users[i]);
22813                        }
22814                        break;
22815                    }
22816                }
22817            }
22818            if (!keep) {
22819                if (DEBUG_CLEAN_APKS) {
22820                    Slog.i(TAG, "  Removing package " + packageName);
22821                }
22822                mHandler.post(new Runnable() {
22823                    public void run() {
22824                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22825                                userHandle, 0);
22826                    } //end run
22827                });
22828            }
22829        }
22830    }
22831
22832    /** Called by UserManagerService */
22833    void createNewUser(int userId, String[] disallowedPackages) {
22834        synchronized (mInstallLock) {
22835            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22836        }
22837        synchronized (mPackages) {
22838            scheduleWritePackageRestrictionsLocked(userId);
22839            scheduleWritePackageListLocked(userId);
22840            applyFactoryDefaultBrowserLPw(userId);
22841            primeDomainVerificationsLPw(userId);
22842        }
22843    }
22844
22845    void onNewUserCreated(final int userId) {
22846        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22847        synchronized(mPackages) {
22848            // If permission review for legacy apps is required, we represent
22849            // dagerous permissions for such apps as always granted runtime
22850            // permissions to keep per user flag state whether review is needed.
22851            // Hence, if a new user is added we have to propagate dangerous
22852            // permission grants for these legacy apps.
22853            if (mSettings.mPermissions.mPermissionReviewRequired) {
22854// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22855                mPermissionManager.updateAllPermissions(
22856                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22857                        mPermissionCallback);
22858            }
22859        }
22860    }
22861
22862    @Override
22863    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22864        mContext.enforceCallingOrSelfPermission(
22865                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22866                "Only package verification agents can read the verifier device identity");
22867
22868        synchronized (mPackages) {
22869            return mSettings.getVerifierDeviceIdentityLPw();
22870        }
22871    }
22872
22873    @Override
22874    public void setPermissionEnforced(String permission, boolean enforced) {
22875        // TODO: Now that we no longer change GID for storage, this should to away.
22876        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22877                "setPermissionEnforced");
22878        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22879            synchronized (mPackages) {
22880                if (mSettings.mReadExternalStorageEnforced == null
22881                        || mSettings.mReadExternalStorageEnforced != enforced) {
22882                    mSettings.mReadExternalStorageEnforced =
22883                            enforced ? Boolean.TRUE : Boolean.FALSE;
22884                    mSettings.writeLPr();
22885                }
22886            }
22887            // kill any non-foreground processes so we restart them and
22888            // grant/revoke the GID.
22889            final IActivityManager am = ActivityManager.getService();
22890            if (am != null) {
22891                final long token = Binder.clearCallingIdentity();
22892                try {
22893                    am.killProcessesBelowForeground("setPermissionEnforcement");
22894                } catch (RemoteException e) {
22895                } finally {
22896                    Binder.restoreCallingIdentity(token);
22897                }
22898            }
22899        } else {
22900            throw new IllegalArgumentException("No selective enforcement for " + permission);
22901        }
22902    }
22903
22904    @Override
22905    @Deprecated
22906    public boolean isPermissionEnforced(String permission) {
22907        // allow instant applications
22908        return true;
22909    }
22910
22911    @Override
22912    public boolean isStorageLow() {
22913        // allow instant applications
22914        final long token = Binder.clearCallingIdentity();
22915        try {
22916            final DeviceStorageMonitorInternal
22917                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22918            if (dsm != null) {
22919                return dsm.isMemoryLow();
22920            } else {
22921                return false;
22922            }
22923        } finally {
22924            Binder.restoreCallingIdentity(token);
22925        }
22926    }
22927
22928    @Override
22929    public IPackageInstaller getPackageInstaller() {
22930        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22931            return null;
22932        }
22933        return mInstallerService;
22934    }
22935
22936    @Override
22937    public IArtManager getArtManager() {
22938        return mArtManagerService;
22939    }
22940
22941    private boolean userNeedsBadging(int userId) {
22942        int index = mUserNeedsBadging.indexOfKey(userId);
22943        if (index < 0) {
22944            final UserInfo userInfo;
22945            final long token = Binder.clearCallingIdentity();
22946            try {
22947                userInfo = sUserManager.getUserInfo(userId);
22948            } finally {
22949                Binder.restoreCallingIdentity(token);
22950            }
22951            final boolean b;
22952            if (userInfo != null && userInfo.isManagedProfile()) {
22953                b = true;
22954            } else {
22955                b = false;
22956            }
22957            mUserNeedsBadging.put(userId, b);
22958            return b;
22959        }
22960        return mUserNeedsBadging.valueAt(index);
22961    }
22962
22963    @Override
22964    public KeySet getKeySetByAlias(String packageName, String alias) {
22965        if (packageName == null || alias == null) {
22966            return null;
22967        }
22968        synchronized(mPackages) {
22969            final PackageParser.Package pkg = mPackages.get(packageName);
22970            if (pkg == null) {
22971                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22972                throw new IllegalArgumentException("Unknown package: " + packageName);
22973            }
22974            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22975            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22976                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22977                throw new IllegalArgumentException("Unknown package: " + packageName);
22978            }
22979            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22980            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22981        }
22982    }
22983
22984    @Override
22985    public KeySet getSigningKeySet(String packageName) {
22986        if (packageName == null) {
22987            return null;
22988        }
22989        synchronized(mPackages) {
22990            final int callingUid = Binder.getCallingUid();
22991            final int callingUserId = UserHandle.getUserId(callingUid);
22992            final PackageParser.Package pkg = mPackages.get(packageName);
22993            if (pkg == null) {
22994                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22995                throw new IllegalArgumentException("Unknown package: " + packageName);
22996            }
22997            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22998            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
22999                // filter and pretend the package doesn't exist
23000                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23001                        + ", uid:" + callingUid);
23002                throw new IllegalArgumentException("Unknown package: " + packageName);
23003            }
23004            if (pkg.applicationInfo.uid != callingUid
23005                    && Process.SYSTEM_UID != callingUid) {
23006                throw new SecurityException("May not access signing KeySet of other apps.");
23007            }
23008            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23009            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23010        }
23011    }
23012
23013    @Override
23014    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23015        final int callingUid = Binder.getCallingUid();
23016        if (getInstantAppPackageName(callingUid) != null) {
23017            return false;
23018        }
23019        if (packageName == null || ks == null) {
23020            return false;
23021        }
23022        synchronized(mPackages) {
23023            final PackageParser.Package pkg = mPackages.get(packageName);
23024            if (pkg == null
23025                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23026                            UserHandle.getUserId(callingUid))) {
23027                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23028                throw new IllegalArgumentException("Unknown package: " + packageName);
23029            }
23030            IBinder ksh = ks.getToken();
23031            if (ksh instanceof KeySetHandle) {
23032                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23033                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23034            }
23035            return false;
23036        }
23037    }
23038
23039    @Override
23040    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23041        final int callingUid = Binder.getCallingUid();
23042        if (getInstantAppPackageName(callingUid) != null) {
23043            return false;
23044        }
23045        if (packageName == null || ks == null) {
23046            return false;
23047        }
23048        synchronized(mPackages) {
23049            final PackageParser.Package pkg = mPackages.get(packageName);
23050            if (pkg == null
23051                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23052                            UserHandle.getUserId(callingUid))) {
23053                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23054                throw new IllegalArgumentException("Unknown package: " + packageName);
23055            }
23056            IBinder ksh = ks.getToken();
23057            if (ksh instanceof KeySetHandle) {
23058                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23059                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23060            }
23061            return false;
23062        }
23063    }
23064
23065    private void deletePackageIfUnusedLPr(final String packageName) {
23066        PackageSetting ps = mSettings.mPackages.get(packageName);
23067        if (ps == null) {
23068            return;
23069        }
23070        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23071            // TODO Implement atomic delete if package is unused
23072            // It is currently possible that the package will be deleted even if it is installed
23073            // after this method returns.
23074            mHandler.post(new Runnable() {
23075                public void run() {
23076                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23077                            0, PackageManager.DELETE_ALL_USERS);
23078                }
23079            });
23080        }
23081    }
23082
23083    /**
23084     * Check and throw if the given before/after packages would be considered a
23085     * downgrade.
23086     */
23087    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23088            throws PackageManagerException {
23089        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23090            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23091                    "Update version code " + after.versionCode + " is older than current "
23092                    + before.getLongVersionCode());
23093        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23094            if (after.baseRevisionCode < before.baseRevisionCode) {
23095                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23096                        "Update base revision code " + after.baseRevisionCode
23097                        + " is older than current " + before.baseRevisionCode);
23098            }
23099
23100            if (!ArrayUtils.isEmpty(after.splitNames)) {
23101                for (int i = 0; i < after.splitNames.length; i++) {
23102                    final String splitName = after.splitNames[i];
23103                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23104                    if (j != -1) {
23105                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23106                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23107                                    "Update split " + splitName + " revision code "
23108                                    + after.splitRevisionCodes[i] + " is older than current "
23109                                    + before.splitRevisionCodes[j]);
23110                        }
23111                    }
23112                }
23113            }
23114        }
23115    }
23116
23117    private static class MoveCallbacks extends Handler {
23118        private static final int MSG_CREATED = 1;
23119        private static final int MSG_STATUS_CHANGED = 2;
23120
23121        private final RemoteCallbackList<IPackageMoveObserver>
23122                mCallbacks = new RemoteCallbackList<>();
23123
23124        private final SparseIntArray mLastStatus = new SparseIntArray();
23125
23126        public MoveCallbacks(Looper looper) {
23127            super(looper);
23128        }
23129
23130        public void register(IPackageMoveObserver callback) {
23131            mCallbacks.register(callback);
23132        }
23133
23134        public void unregister(IPackageMoveObserver callback) {
23135            mCallbacks.unregister(callback);
23136        }
23137
23138        @Override
23139        public void handleMessage(Message msg) {
23140            final SomeArgs args = (SomeArgs) msg.obj;
23141            final int n = mCallbacks.beginBroadcast();
23142            for (int i = 0; i < n; i++) {
23143                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23144                try {
23145                    invokeCallback(callback, msg.what, args);
23146                } catch (RemoteException ignored) {
23147                }
23148            }
23149            mCallbacks.finishBroadcast();
23150            args.recycle();
23151        }
23152
23153        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23154                throws RemoteException {
23155            switch (what) {
23156                case MSG_CREATED: {
23157                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23158                    break;
23159                }
23160                case MSG_STATUS_CHANGED: {
23161                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23162                    break;
23163                }
23164            }
23165        }
23166
23167        private void notifyCreated(int moveId, Bundle extras) {
23168            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23169
23170            final SomeArgs args = SomeArgs.obtain();
23171            args.argi1 = moveId;
23172            args.arg2 = extras;
23173            obtainMessage(MSG_CREATED, args).sendToTarget();
23174        }
23175
23176        private void notifyStatusChanged(int moveId, int status) {
23177            notifyStatusChanged(moveId, status, -1);
23178        }
23179
23180        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23181            Slog.v(TAG, "Move " + moveId + " status " + status);
23182
23183            final SomeArgs args = SomeArgs.obtain();
23184            args.argi1 = moveId;
23185            args.argi2 = status;
23186            args.arg3 = estMillis;
23187            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23188
23189            synchronized (mLastStatus) {
23190                mLastStatus.put(moveId, status);
23191            }
23192        }
23193    }
23194
23195    private final static class OnPermissionChangeListeners extends Handler {
23196        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23197
23198        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23199                new RemoteCallbackList<>();
23200
23201        public OnPermissionChangeListeners(Looper looper) {
23202            super(looper);
23203        }
23204
23205        @Override
23206        public void handleMessage(Message msg) {
23207            switch (msg.what) {
23208                case MSG_ON_PERMISSIONS_CHANGED: {
23209                    final int uid = msg.arg1;
23210                    handleOnPermissionsChanged(uid);
23211                } break;
23212            }
23213        }
23214
23215        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23216            mPermissionListeners.register(listener);
23217
23218        }
23219
23220        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23221            mPermissionListeners.unregister(listener);
23222        }
23223
23224        public void onPermissionsChanged(int uid) {
23225            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23226                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23227            }
23228        }
23229
23230        private void handleOnPermissionsChanged(int uid) {
23231            final int count = mPermissionListeners.beginBroadcast();
23232            try {
23233                for (int i = 0; i < count; i++) {
23234                    IOnPermissionsChangeListener callback = mPermissionListeners
23235                            .getBroadcastItem(i);
23236                    try {
23237                        callback.onPermissionsChanged(uid);
23238                    } catch (RemoteException e) {
23239                        Log.e(TAG, "Permission listener is dead", e);
23240                    }
23241                }
23242            } finally {
23243                mPermissionListeners.finishBroadcast();
23244            }
23245        }
23246    }
23247
23248    private class PackageManagerNative extends IPackageManagerNative.Stub {
23249        @Override
23250        public String[] getNamesForUids(int[] uids) throws RemoteException {
23251            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23252            // massage results so they can be parsed by the native binder
23253            for (int i = results.length - 1; i >= 0; --i) {
23254                if (results[i] == null) {
23255                    results[i] = "";
23256                }
23257            }
23258            return results;
23259        }
23260
23261        // NB: this differentiates between preloads and sideloads
23262        @Override
23263        public String getInstallerForPackage(String packageName) throws RemoteException {
23264            final String installerName = getInstallerPackageName(packageName);
23265            if (!TextUtils.isEmpty(installerName)) {
23266                return installerName;
23267            }
23268            // differentiate between preload and sideload
23269            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23270            ApplicationInfo appInfo = getApplicationInfo(packageName,
23271                                    /*flags*/ 0,
23272                                    /*userId*/ callingUser);
23273            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23274                return "preload";
23275            }
23276            return "";
23277        }
23278
23279        @Override
23280        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23281            try {
23282                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23283                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23284                if (pInfo != null) {
23285                    return pInfo.getLongVersionCode();
23286                }
23287            } catch (Exception e) {
23288            }
23289            return 0;
23290        }
23291    }
23292
23293    private class PackageManagerInternalImpl extends PackageManagerInternal {
23294        @Override
23295        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23296                int flagValues, int userId) {
23297            PackageManagerService.this.updatePermissionFlags(
23298                    permName, packageName, flagMask, flagValues, userId);
23299        }
23300
23301        @Override
23302        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23303            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23304        }
23305
23306        @Override
23307        public boolean isInstantApp(String packageName, int userId) {
23308            return PackageManagerService.this.isInstantApp(packageName, userId);
23309        }
23310
23311        @Override
23312        public String getInstantAppPackageName(int uid) {
23313            return PackageManagerService.this.getInstantAppPackageName(uid);
23314        }
23315
23316        @Override
23317        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23318            synchronized (mPackages) {
23319                return PackageManagerService.this.filterAppAccessLPr(
23320                        (PackageSetting) pkg.mExtras, callingUid, userId);
23321            }
23322        }
23323
23324        @Override
23325        public PackageParser.Package getPackage(String packageName) {
23326            synchronized (mPackages) {
23327                packageName = resolveInternalPackageNameLPr(
23328                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23329                return mPackages.get(packageName);
23330            }
23331        }
23332
23333        @Override
23334        public PackageList getPackageList(PackageListObserver observer) {
23335            synchronized (mPackages) {
23336                final int N = mPackages.size();
23337                final ArrayList<String> list = new ArrayList<>(N);
23338                for (int i = 0; i < N; i++) {
23339                    list.add(mPackages.keyAt(i));
23340                }
23341                final PackageList packageList = new PackageList(list, observer);
23342                if (observer != null) {
23343                    mPackageListObservers.add(packageList);
23344                }
23345                return packageList;
23346            }
23347        }
23348
23349        @Override
23350        public void removePackageListObserver(PackageListObserver observer) {
23351            synchronized (mPackages) {
23352                mPackageListObservers.remove(observer);
23353            }
23354        }
23355
23356        @Override
23357        public PackageParser.Package getDisabledPackage(String packageName) {
23358            synchronized (mPackages) {
23359                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23360                return (ps != null) ? ps.pkg : null;
23361            }
23362        }
23363
23364        @Override
23365        public String getKnownPackageName(int knownPackage, int userId) {
23366            switch(knownPackage) {
23367                case PackageManagerInternal.PACKAGE_BROWSER:
23368                    return getDefaultBrowserPackageName(userId);
23369                case PackageManagerInternal.PACKAGE_INSTALLER:
23370                    return mRequiredInstallerPackage;
23371                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23372                    return mSetupWizardPackage;
23373                case PackageManagerInternal.PACKAGE_SYSTEM:
23374                    return "android";
23375                case PackageManagerInternal.PACKAGE_VERIFIER:
23376                    return mRequiredVerifierPackage;
23377            }
23378            return null;
23379        }
23380
23381        @Override
23382        public boolean isResolveActivityComponent(ComponentInfo component) {
23383            return mResolveActivity.packageName.equals(component.packageName)
23384                    && mResolveActivity.name.equals(component.name);
23385        }
23386
23387        @Override
23388        public void setLocationPackagesProvider(PackagesProvider provider) {
23389            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23390        }
23391
23392        @Override
23393        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23394            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23395        }
23396
23397        @Override
23398        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23399            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23400        }
23401
23402        @Override
23403        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23404            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23405        }
23406
23407        @Override
23408        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23409            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23410        }
23411
23412        @Override
23413        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23414            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23415        }
23416
23417        @Override
23418        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23419            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23420        }
23421
23422        @Override
23423        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23424            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23425        }
23426
23427        @Override
23428        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23429            synchronized (mPackages) {
23430                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23431            }
23432            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23433        }
23434
23435        @Override
23436        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23437            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23438                    packageName, userId);
23439        }
23440
23441        @Override
23442        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23443            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23444                    packageName, userId);
23445        }
23446
23447        @Override
23448        public void setKeepUninstalledPackages(final List<String> packageList) {
23449            Preconditions.checkNotNull(packageList);
23450            List<String> removedFromList = null;
23451            synchronized (mPackages) {
23452                if (mKeepUninstalledPackages != null) {
23453                    final int packagesCount = mKeepUninstalledPackages.size();
23454                    for (int i = 0; i < packagesCount; i++) {
23455                        String oldPackage = mKeepUninstalledPackages.get(i);
23456                        if (packageList != null && packageList.contains(oldPackage)) {
23457                            continue;
23458                        }
23459                        if (removedFromList == null) {
23460                            removedFromList = new ArrayList<>();
23461                        }
23462                        removedFromList.add(oldPackage);
23463                    }
23464                }
23465                mKeepUninstalledPackages = new ArrayList<>(packageList);
23466                if (removedFromList != null) {
23467                    final int removedCount = removedFromList.size();
23468                    for (int i = 0; i < removedCount; i++) {
23469                        deletePackageIfUnusedLPr(removedFromList.get(i));
23470                    }
23471                }
23472            }
23473        }
23474
23475        @Override
23476        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23477            synchronized (mPackages) {
23478                return mPermissionManager.isPermissionsReviewRequired(
23479                        mPackages.get(packageName), userId);
23480            }
23481        }
23482
23483        @Override
23484        public PackageInfo getPackageInfo(
23485                String packageName, int flags, int filterCallingUid, int userId) {
23486            return PackageManagerService.this
23487                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23488                            flags, filterCallingUid, userId);
23489        }
23490
23491        @Override
23492        public int getPackageUid(String packageName, int flags, int userId) {
23493            return PackageManagerService.this
23494                    .getPackageUid(packageName, flags, userId);
23495        }
23496
23497        @Override
23498        public ApplicationInfo getApplicationInfo(
23499                String packageName, int flags, int filterCallingUid, int userId) {
23500            return PackageManagerService.this
23501                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23502        }
23503
23504        @Override
23505        public ActivityInfo getActivityInfo(
23506                ComponentName component, int flags, int filterCallingUid, int userId) {
23507            return PackageManagerService.this
23508                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23509        }
23510
23511        @Override
23512        public List<ResolveInfo> queryIntentActivities(
23513                Intent intent, int flags, int filterCallingUid, int userId) {
23514            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23515            return PackageManagerService.this
23516                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23517                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23518        }
23519
23520        @Override
23521        public List<ResolveInfo> queryIntentServices(
23522                Intent intent, int flags, int callingUid, int userId) {
23523            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23524            return PackageManagerService.this
23525                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23526                            false);
23527        }
23528
23529        @Override
23530        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23531                int userId) {
23532            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23533        }
23534
23535        @Override
23536        public void setDeviceAndProfileOwnerPackages(
23537                int deviceOwnerUserId, String deviceOwnerPackage,
23538                SparseArray<String> profileOwnerPackages) {
23539            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23540                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23541        }
23542
23543        @Override
23544        public boolean isPackageDataProtected(int userId, String packageName) {
23545            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23546        }
23547
23548        @Override
23549        public boolean isPackageEphemeral(int userId, String packageName) {
23550            synchronized (mPackages) {
23551                final PackageSetting ps = mSettings.mPackages.get(packageName);
23552                return ps != null ? ps.getInstantApp(userId) : false;
23553            }
23554        }
23555
23556        @Override
23557        public boolean wasPackageEverLaunched(String packageName, int userId) {
23558            synchronized (mPackages) {
23559                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23560            }
23561        }
23562
23563        @Override
23564        public void grantRuntimePermission(String packageName, String permName, int userId,
23565                boolean overridePolicy) {
23566            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23567                    permName, packageName, overridePolicy, getCallingUid(), userId,
23568                    mPermissionCallback);
23569        }
23570
23571        @Override
23572        public void revokeRuntimePermission(String packageName, String permName, int userId,
23573                boolean overridePolicy) {
23574            mPermissionManager.revokeRuntimePermission(
23575                    permName, packageName, overridePolicy, getCallingUid(), userId,
23576                    mPermissionCallback);
23577        }
23578
23579        @Override
23580        public String getNameForUid(int uid) {
23581            return PackageManagerService.this.getNameForUid(uid);
23582        }
23583
23584        @Override
23585        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23586                Intent origIntent, String resolvedType, String callingPackage,
23587                Bundle verificationBundle, int userId) {
23588            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23589                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23590                    userId);
23591        }
23592
23593        @Override
23594        public void grantEphemeralAccess(int userId, Intent intent,
23595                int targetAppId, int ephemeralAppId) {
23596            synchronized (mPackages) {
23597                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23598                        targetAppId, ephemeralAppId);
23599            }
23600        }
23601
23602        @Override
23603        public boolean isInstantAppInstallerComponent(ComponentName component) {
23604            synchronized (mPackages) {
23605                return mInstantAppInstallerActivity != null
23606                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23607            }
23608        }
23609
23610        @Override
23611        public void pruneInstantApps() {
23612            mInstantAppRegistry.pruneInstantApps();
23613        }
23614
23615        @Override
23616        public String getSetupWizardPackageName() {
23617            return mSetupWizardPackage;
23618        }
23619
23620        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23621            if (policy != null) {
23622                mExternalSourcesPolicy = policy;
23623            }
23624        }
23625
23626        @Override
23627        public boolean isPackagePersistent(String packageName) {
23628            synchronized (mPackages) {
23629                PackageParser.Package pkg = mPackages.get(packageName);
23630                return pkg != null
23631                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23632                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23633                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23634                        : false;
23635            }
23636        }
23637
23638        @Override
23639        public boolean isLegacySystemApp(Package pkg) {
23640            synchronized (mPackages) {
23641                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23642                return mPromoteSystemApps
23643                        && ps.isSystem()
23644                        && mExistingSystemPackages.contains(ps.name);
23645            }
23646        }
23647
23648        @Override
23649        public List<PackageInfo> getOverlayPackages(int userId) {
23650            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23651            synchronized (mPackages) {
23652                for (PackageParser.Package p : mPackages.values()) {
23653                    if (p.mOverlayTarget != null) {
23654                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23655                        if (pkg != null) {
23656                            overlayPackages.add(pkg);
23657                        }
23658                    }
23659                }
23660            }
23661            return overlayPackages;
23662        }
23663
23664        @Override
23665        public List<String> getTargetPackageNames(int userId) {
23666            List<String> targetPackages = new ArrayList<>();
23667            synchronized (mPackages) {
23668                for (PackageParser.Package p : mPackages.values()) {
23669                    if (p.mOverlayTarget == null) {
23670                        targetPackages.add(p.packageName);
23671                    }
23672                }
23673            }
23674            return targetPackages;
23675        }
23676
23677        @Override
23678        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23679                @Nullable List<String> overlayPackageNames) {
23680            synchronized (mPackages) {
23681                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23682                    Slog.e(TAG, "failed to find package " + targetPackageName);
23683                    return false;
23684                }
23685                ArrayList<String> overlayPaths = null;
23686                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23687                    final int N = overlayPackageNames.size();
23688                    overlayPaths = new ArrayList<>(N);
23689                    for (int i = 0; i < N; i++) {
23690                        final String packageName = overlayPackageNames.get(i);
23691                        final PackageParser.Package pkg = mPackages.get(packageName);
23692                        if (pkg == null) {
23693                            Slog.e(TAG, "failed to find package " + packageName);
23694                            return false;
23695                        }
23696                        overlayPaths.add(pkg.baseCodePath);
23697                    }
23698                }
23699
23700                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23701                ps.setOverlayPaths(overlayPaths, userId);
23702                return true;
23703            }
23704        }
23705
23706        @Override
23707        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23708                int flags, int userId, boolean resolveForStart) {
23709            return resolveIntentInternal(
23710                    intent, resolvedType, flags, userId, resolveForStart);
23711        }
23712
23713        @Override
23714        public ResolveInfo resolveService(Intent intent, String resolvedType,
23715                int flags, int userId, int callingUid) {
23716            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23717        }
23718
23719        @Override
23720        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23721            return PackageManagerService.this.resolveContentProviderInternal(
23722                    name, flags, userId);
23723        }
23724
23725        @Override
23726        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23727            synchronized (mPackages) {
23728                mIsolatedOwners.put(isolatedUid, ownerUid);
23729            }
23730        }
23731
23732        @Override
23733        public void removeIsolatedUid(int isolatedUid) {
23734            synchronized (mPackages) {
23735                mIsolatedOwners.delete(isolatedUid);
23736            }
23737        }
23738
23739        @Override
23740        public int getUidTargetSdkVersion(int uid) {
23741            synchronized (mPackages) {
23742                return getUidTargetSdkVersionLockedLPr(uid);
23743            }
23744        }
23745
23746        @Override
23747        public int getPackageTargetSdkVersion(String packageName) {
23748            synchronized (mPackages) {
23749                return getPackageTargetSdkVersionLockedLPr(packageName);
23750            }
23751        }
23752
23753        @Override
23754        public boolean canAccessInstantApps(int callingUid, int userId) {
23755            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23756        }
23757
23758        @Override
23759        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23760            synchronized (mPackages) {
23761                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23762            }
23763        }
23764
23765        @Override
23766        public void notifyPackageUse(String packageName, int reason) {
23767            synchronized (mPackages) {
23768                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23769            }
23770        }
23771    }
23772
23773    @Override
23774    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23775        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23776        synchronized (mPackages) {
23777            final long identity = Binder.clearCallingIdentity();
23778            try {
23779                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23780                        packageNames, userId);
23781            } finally {
23782                Binder.restoreCallingIdentity(identity);
23783            }
23784        }
23785    }
23786
23787    @Override
23788    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23789        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23790        synchronized (mPackages) {
23791            final long identity = Binder.clearCallingIdentity();
23792            try {
23793                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23794                        packageNames, userId);
23795            } finally {
23796                Binder.restoreCallingIdentity(identity);
23797            }
23798        }
23799    }
23800
23801    private static void enforceSystemOrPhoneCaller(String tag) {
23802        int callingUid = Binder.getCallingUid();
23803        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23804            throw new SecurityException(
23805                    "Cannot call " + tag + " from UID " + callingUid);
23806        }
23807    }
23808
23809    boolean isHistoricalPackageUsageAvailable() {
23810        return mPackageUsage.isHistoricalPackageUsageAvailable();
23811    }
23812
23813    /**
23814     * Return a <b>copy</b> of the collection of packages known to the package manager.
23815     * @return A copy of the values of mPackages.
23816     */
23817    Collection<PackageParser.Package> getPackages() {
23818        synchronized (mPackages) {
23819            return new ArrayList<>(mPackages.values());
23820        }
23821    }
23822
23823    /**
23824     * Logs process start information (including base APK hash) to the security log.
23825     * @hide
23826     */
23827    @Override
23828    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23829            String apkFile, int pid) {
23830        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23831            return;
23832        }
23833        if (!SecurityLog.isLoggingEnabled()) {
23834            return;
23835        }
23836        Bundle data = new Bundle();
23837        data.putLong("startTimestamp", System.currentTimeMillis());
23838        data.putString("processName", processName);
23839        data.putInt("uid", uid);
23840        data.putString("seinfo", seinfo);
23841        data.putString("apkFile", apkFile);
23842        data.putInt("pid", pid);
23843        Message msg = mProcessLoggingHandler.obtainMessage(
23844                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23845        msg.setData(data);
23846        mProcessLoggingHandler.sendMessage(msg);
23847    }
23848
23849    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23850        return mCompilerStats.getPackageStats(pkgName);
23851    }
23852
23853    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23854        return getOrCreateCompilerPackageStats(pkg.packageName);
23855    }
23856
23857    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23858        return mCompilerStats.getOrCreatePackageStats(pkgName);
23859    }
23860
23861    public void deleteCompilerPackageStats(String pkgName) {
23862        mCompilerStats.deletePackageStats(pkgName);
23863    }
23864
23865    @Override
23866    public int getInstallReason(String packageName, int userId) {
23867        final int callingUid = Binder.getCallingUid();
23868        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23869                true /* requireFullPermission */, false /* checkShell */,
23870                "get install reason");
23871        synchronized (mPackages) {
23872            final PackageSetting ps = mSettings.mPackages.get(packageName);
23873            if (filterAppAccessLPr(ps, callingUid, userId)) {
23874                return PackageManager.INSTALL_REASON_UNKNOWN;
23875            }
23876            if (ps != null) {
23877                return ps.getInstallReason(userId);
23878            }
23879        }
23880        return PackageManager.INSTALL_REASON_UNKNOWN;
23881    }
23882
23883    @Override
23884    public boolean canRequestPackageInstalls(String packageName, int userId) {
23885        return canRequestPackageInstallsInternal(packageName, 0, userId,
23886                true /* throwIfPermNotDeclared*/);
23887    }
23888
23889    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23890            boolean throwIfPermNotDeclared) {
23891        int callingUid = Binder.getCallingUid();
23892        int uid = getPackageUid(packageName, 0, userId);
23893        if (callingUid != uid && callingUid != Process.ROOT_UID
23894                && callingUid != Process.SYSTEM_UID) {
23895            throw new SecurityException(
23896                    "Caller uid " + callingUid + " does not own package " + packageName);
23897        }
23898        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23899        if (info == null) {
23900            return false;
23901        }
23902        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23903            return false;
23904        }
23905        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23906        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23907        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23908            if (throwIfPermNotDeclared) {
23909                throw new SecurityException("Need to declare " + appOpPermission
23910                        + " to call this api");
23911            } else {
23912                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23913                return false;
23914            }
23915        }
23916        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23917            return false;
23918        }
23919        if (mExternalSourcesPolicy != null) {
23920            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23921            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23922                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23923            }
23924        }
23925        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23926    }
23927
23928    @Override
23929    public ComponentName getInstantAppResolverSettingsComponent() {
23930        return mInstantAppResolverSettingsComponent;
23931    }
23932
23933    @Override
23934    public ComponentName getInstantAppInstallerComponent() {
23935        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23936            return null;
23937        }
23938        return mInstantAppInstallerActivity == null
23939                ? null : mInstantAppInstallerActivity.getComponentName();
23940    }
23941
23942    @Override
23943    public String getInstantAppAndroidId(String packageName, int userId) {
23944        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23945                "getInstantAppAndroidId");
23946        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23947                true /* requireFullPermission */, false /* checkShell */,
23948                "getInstantAppAndroidId");
23949        // Make sure the target is an Instant App.
23950        if (!isInstantApp(packageName, userId)) {
23951            return null;
23952        }
23953        synchronized (mPackages) {
23954            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23955        }
23956    }
23957
23958    boolean canHaveOatDir(String packageName) {
23959        synchronized (mPackages) {
23960            PackageParser.Package p = mPackages.get(packageName);
23961            if (p == null) {
23962                return false;
23963            }
23964            return p.canHaveOatDir();
23965        }
23966    }
23967
23968    private String getOatDir(PackageParser.Package pkg) {
23969        if (!pkg.canHaveOatDir()) {
23970            return null;
23971        }
23972        File codePath = new File(pkg.codePath);
23973        if (codePath.isDirectory()) {
23974            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23975        }
23976        return null;
23977    }
23978
23979    void deleteOatArtifactsOfPackage(String packageName) {
23980        final String[] instructionSets;
23981        final List<String> codePaths;
23982        final String oatDir;
23983        final PackageParser.Package pkg;
23984        synchronized (mPackages) {
23985            pkg = mPackages.get(packageName);
23986        }
23987        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
23988        codePaths = pkg.getAllCodePaths();
23989        oatDir = getOatDir(pkg);
23990
23991        for (String codePath : codePaths) {
23992            for (String isa : instructionSets) {
23993                try {
23994                    mInstaller.deleteOdex(codePath, isa, oatDir);
23995                } catch (InstallerException e) {
23996                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
23997                }
23998            }
23999        }
24000    }
24001
24002    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24003        Set<String> unusedPackages = new HashSet<>();
24004        long currentTimeInMillis = System.currentTimeMillis();
24005        synchronized (mPackages) {
24006            for (PackageParser.Package pkg : mPackages.values()) {
24007                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24008                if (ps == null) {
24009                    continue;
24010                }
24011                PackageDexUsage.PackageUseInfo packageUseInfo =
24012                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24013                if (PackageManagerServiceUtils
24014                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24015                                downgradeTimeThresholdMillis, packageUseInfo,
24016                                pkg.getLatestPackageUseTimeInMills(),
24017                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24018                    unusedPackages.add(pkg.packageName);
24019                }
24020            }
24021        }
24022        return unusedPackages;
24023    }
24024
24025    @Override
24026    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24027            int userId) {
24028        final int callingUid = Binder.getCallingUid();
24029        final int callingAppId = UserHandle.getAppId(callingUid);
24030
24031        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24032                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24033
24034        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24035                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24036            throw new SecurityException("Caller must have the "
24037                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24038        }
24039
24040        synchronized(mPackages) {
24041            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24042            scheduleWritePackageRestrictionsLocked(userId);
24043        }
24044    }
24045
24046    @Nullable
24047    @Override
24048    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24049        final int callingUid = Binder.getCallingUid();
24050        final int callingAppId = UserHandle.getAppId(callingUid);
24051
24052        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24053                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24054
24055        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24056                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24057            throw new SecurityException("Caller must have the "
24058                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24059        }
24060
24061        synchronized(mPackages) {
24062            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24063        }
24064    }
24065}
24066
24067interface PackageSender {
24068    /**
24069     * @param userIds User IDs where the action occurred on a full application
24070     * @param instantUserIds User IDs where the action occurred on an instant application
24071     */
24072    void sendPackageBroadcast(final String action, final String pkg,
24073        final Bundle extras, final int flags, final String targetPkg,
24074        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24075    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24076        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24077    void notifyPackageAdded(String packageName);
24078    void notifyPackageRemoved(String packageName);
24079}
24080