PackageManagerService.java revision 26fd4ce67bed27688c7320b57078e89a9c22124d
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        @GuardedBy("mInstallLock")
801        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
802                String targetPackageName, String targetPath) {
803            if ("android".equals(targetPackageName)) {
804                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
805                // native AssetManager.
806                return null;
807            }
808            List<PackageParser.Package> overlayPackages =
809                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
810            if (overlayPackages == null || overlayPackages.isEmpty()) {
811                return null;
812            }
813            List<String> overlayPathList = null;
814            for (PackageParser.Package overlayPackage : overlayPackages) {
815                if (targetPath == null) {
816                    if (overlayPathList == null) {
817                        overlayPathList = new ArrayList<String>();
818                    }
819                    overlayPathList.add(overlayPackage.baseCodePath);
820                    continue;
821                }
822
823                try {
824                    // Creates idmaps for system to parse correctly the Android manifest of the
825                    // target package.
826                    //
827                    // OverlayManagerService will update each of them with a correct gid from its
828                    // target package app id.
829                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
830                            UserHandle.getSharedAppGid(
831                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
832                    if (overlayPathList == null) {
833                        overlayPathList = new ArrayList<String>();
834                    }
835                    overlayPathList.add(overlayPackage.baseCodePath);
836                } catch (InstallerException e) {
837                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
838                            overlayPackage.baseCodePath);
839                }
840            }
841            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
842        }
843
844        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
845            synchronized (mPackages) {
846                return getStaticOverlayPathsLocked(
847                        mPackages.values(), targetPackageName, targetPath);
848            }
849        }
850
851        @Override public final String[] getOverlayApks(String targetPackageName) {
852            return getStaticOverlayPaths(targetPackageName, null);
853        }
854
855        @Override public final String[] getOverlayPaths(String targetPackageName,
856                String targetPath) {
857            return getStaticOverlayPaths(targetPackageName, targetPath);
858        }
859    }
860
861    class ParallelPackageParserCallback extends PackageParserCallback {
862        List<PackageParser.Package> mOverlayPackages = null;
863
864        void findStaticOverlayPackages() {
865            synchronized (mPackages) {
866                for (PackageParser.Package p : mPackages.values()) {
867                    if (p.mOverlayIsStatic) {
868                        if (mOverlayPackages == null) {
869                            mOverlayPackages = new ArrayList<PackageParser.Package>();
870                        }
871                        mOverlayPackages.add(p);
872                    }
873                }
874            }
875        }
876
877        @Override
878        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
879            // We can trust mOverlayPackages without holding mPackages because package uninstall
880            // can't happen while running parallel parsing.
881            // Moreover holding mPackages on each parsing thread causes dead-lock.
882            return mOverlayPackages == null ? null :
883                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
884        }
885    }
886
887    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
888    final ParallelPackageParserCallback mParallelPackageParserCallback =
889            new ParallelPackageParserCallback();
890
891    public static final class SharedLibraryEntry {
892        public final @Nullable String path;
893        public final @Nullable String apk;
894        public final @NonNull SharedLibraryInfo info;
895
896        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
897                String declaringPackageName, long declaringPackageVersionCode) {
898            path = _path;
899            apk = _apk;
900            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
901                    declaringPackageName, declaringPackageVersionCode), null);
902        }
903    }
904
905    // Currently known shared libraries.
906    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
907    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
908            new ArrayMap<>();
909
910    // All available activities, for your resolving pleasure.
911    final ActivityIntentResolver mActivities =
912            new ActivityIntentResolver();
913
914    // All available receivers, for your resolving pleasure.
915    final ActivityIntentResolver mReceivers =
916            new ActivityIntentResolver();
917
918    // All available services, for your resolving pleasure.
919    final ServiceIntentResolver mServices = new ServiceIntentResolver();
920
921    // All available providers, for your resolving pleasure.
922    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
923
924    // Mapping from provider base names (first directory in content URI codePath)
925    // to the provider information.
926    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
927            new ArrayMap<String, PackageParser.Provider>();
928
929    // Mapping from instrumentation class names to info about them.
930    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
931            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
932
933    // Packages whose data we have transfered into another package, thus
934    // should no longer exist.
935    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
936
937    // Broadcast actions that are only available to the system.
938    @GuardedBy("mProtectedBroadcasts")
939    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
940
941    /** List of packages waiting for verification. */
942    final SparseArray<PackageVerificationState> mPendingVerification
943            = new SparseArray<PackageVerificationState>();
944
945    final PackageInstallerService mInstallerService;
946
947    final ArtManagerService mArtManagerService;
948
949    private final PackageDexOptimizer mPackageDexOptimizer;
950    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
951    // is used by other apps).
952    private final DexManager mDexManager;
953
954    private AtomicInteger mNextMoveId = new AtomicInteger();
955    private final MoveCallbacks mMoveCallbacks;
956
957    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
958
959    // Cache of users who need badging.
960    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
961
962    /** Token for keys in mPendingVerification. */
963    private int mPendingVerificationToken = 0;
964
965    volatile boolean mSystemReady;
966    volatile boolean mSafeMode;
967    volatile boolean mHasSystemUidErrors;
968    private volatile boolean mWebInstantAppsDisabled;
969
970    ApplicationInfo mAndroidApplication;
971    final ActivityInfo mResolveActivity = new ActivityInfo();
972    final ResolveInfo mResolveInfo = new ResolveInfo();
973    ComponentName mResolveComponentName;
974    PackageParser.Package mPlatformPackage;
975    ComponentName mCustomResolverComponentName;
976
977    boolean mResolverReplaced = false;
978
979    private final @Nullable ComponentName mIntentFilterVerifierComponent;
980    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
981
982    private int mIntentFilterVerificationToken = 0;
983
984    /** The service connection to the ephemeral resolver */
985    final InstantAppResolverConnection mInstantAppResolverConnection;
986    /** Component used to show resolver settings for Instant Apps */
987    final ComponentName mInstantAppResolverSettingsComponent;
988
989    /** Activity used to install instant applications */
990    ActivityInfo mInstantAppInstallerActivity;
991    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
992
993    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
994            = new SparseArray<IntentFilterVerificationState>();
995
996    // TODO remove this and go through mPermissonManager directly
997    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
998    private final PermissionManagerInternal mPermissionManager;
999
1000    // List of packages names to keep cached, even if they are uninstalled for all users
1001    private List<String> mKeepUninstalledPackages;
1002
1003    private UserManagerInternal mUserManagerInternal;
1004    private ActivityManagerInternal mActivityManagerInternal;
1005
1006    private DeviceIdleController.LocalService mDeviceIdleController;
1007
1008    private File mCacheDir;
1009
1010    private Future<?> mPrepareAppDataFuture;
1011
1012    private static class IFVerificationParams {
1013        PackageParser.Package pkg;
1014        boolean replacing;
1015        int userId;
1016        int verifierUid;
1017
1018        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1019                int _userId, int _verifierUid) {
1020            pkg = _pkg;
1021            replacing = _replacing;
1022            userId = _userId;
1023            replacing = _replacing;
1024            verifierUid = _verifierUid;
1025        }
1026    }
1027
1028    private interface IntentFilterVerifier<T extends IntentFilter> {
1029        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1030                                               T filter, String packageName);
1031        void startVerifications(int userId);
1032        void receiveVerificationResponse(int verificationId);
1033    }
1034
1035    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1036        private Context mContext;
1037        private ComponentName mIntentFilterVerifierComponent;
1038        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1039
1040        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1041            mContext = context;
1042            mIntentFilterVerifierComponent = verifierComponent;
1043        }
1044
1045        private String getDefaultScheme() {
1046            return IntentFilter.SCHEME_HTTPS;
1047        }
1048
1049        @Override
1050        public void startVerifications(int userId) {
1051            // Launch verifications requests
1052            int count = mCurrentIntentFilterVerifications.size();
1053            for (int n=0; n<count; n++) {
1054                int verificationId = mCurrentIntentFilterVerifications.get(n);
1055                final IntentFilterVerificationState ivs =
1056                        mIntentFilterVerificationStates.get(verificationId);
1057
1058                String packageName = ivs.getPackageName();
1059
1060                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1061                final int filterCount = filters.size();
1062                ArraySet<String> domainsSet = new ArraySet<>();
1063                for (int m=0; m<filterCount; m++) {
1064                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1065                    domainsSet.addAll(filter.getHostsList());
1066                }
1067                synchronized (mPackages) {
1068                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1069                            packageName, domainsSet) != null) {
1070                        scheduleWriteSettingsLocked();
1071                    }
1072                }
1073                sendVerificationRequest(verificationId, ivs);
1074            }
1075            mCurrentIntentFilterVerifications.clear();
1076        }
1077
1078        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1079            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1080            verificationIntent.putExtra(
1081                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1082                    verificationId);
1083            verificationIntent.putExtra(
1084                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1085                    getDefaultScheme());
1086            verificationIntent.putExtra(
1087                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1088                    ivs.getHostsString());
1089            verificationIntent.putExtra(
1090                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1091                    ivs.getPackageName());
1092            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1093            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1094
1095            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1096            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1097                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1098                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1099
1100            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1101            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1102                    "Sending IntentFilter verification broadcast");
1103        }
1104
1105        public void receiveVerificationResponse(int verificationId) {
1106            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1107
1108            final boolean verified = ivs.isVerified();
1109
1110            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1111            final int count = filters.size();
1112            if (DEBUG_DOMAIN_VERIFICATION) {
1113                Slog.i(TAG, "Received verification response " + verificationId
1114                        + " for " + count + " filters, verified=" + verified);
1115            }
1116            for (int n=0; n<count; n++) {
1117                PackageParser.ActivityIntentInfo filter = filters.get(n);
1118                filter.setVerified(verified);
1119
1120                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1121                        + " verified with result:" + verified + " and hosts:"
1122                        + ivs.getHostsString());
1123            }
1124
1125            mIntentFilterVerificationStates.remove(verificationId);
1126
1127            final String packageName = ivs.getPackageName();
1128            IntentFilterVerificationInfo ivi = null;
1129
1130            synchronized (mPackages) {
1131                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1132            }
1133            if (ivi == null) {
1134                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1135                        + verificationId + " packageName:" + packageName);
1136                return;
1137            }
1138            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1139                    "Updating IntentFilterVerificationInfo for package " + packageName
1140                            +" verificationId:" + verificationId);
1141
1142            synchronized (mPackages) {
1143                if (verified) {
1144                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1145                } else {
1146                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1147                }
1148                scheduleWriteSettingsLocked();
1149
1150                final int userId = ivs.getUserId();
1151                if (userId != UserHandle.USER_ALL) {
1152                    final int userStatus =
1153                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1154
1155                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1156                    boolean needUpdate = false;
1157
1158                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1159                    // already been set by the User thru the Disambiguation dialog
1160                    switch (userStatus) {
1161                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1162                            if (verified) {
1163                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1164                            } else {
1165                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1166                            }
1167                            needUpdate = true;
1168                            break;
1169
1170                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1171                            if (verified) {
1172                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1173                                needUpdate = true;
1174                            }
1175                            break;
1176
1177                        default:
1178                            // Nothing to do
1179                    }
1180
1181                    if (needUpdate) {
1182                        mSettings.updateIntentFilterVerificationStatusLPw(
1183                                packageName, updatedStatus, userId);
1184                        scheduleWritePackageRestrictionsLocked(userId);
1185                    }
1186                }
1187            }
1188        }
1189
1190        @Override
1191        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1192                    ActivityIntentInfo filter, String packageName) {
1193            if (!hasValidDomains(filter)) {
1194                return false;
1195            }
1196            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1197            if (ivs == null) {
1198                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1199                        packageName);
1200            }
1201            if (DEBUG_DOMAIN_VERIFICATION) {
1202                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1203            }
1204            ivs.addFilter(filter);
1205            return true;
1206        }
1207
1208        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1209                int userId, int verificationId, String packageName) {
1210            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1211                    verifierUid, userId, packageName);
1212            ivs.setPendingState();
1213            synchronized (mPackages) {
1214                mIntentFilterVerificationStates.append(verificationId, ivs);
1215                mCurrentIntentFilterVerifications.add(verificationId);
1216            }
1217            return ivs;
1218        }
1219    }
1220
1221    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1222        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1223                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1224                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1225    }
1226
1227    // Set of pending broadcasts for aggregating enable/disable of components.
1228    static class PendingPackageBroadcasts {
1229        // for each user id, a map of <package name -> components within that package>
1230        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1231
1232        public PendingPackageBroadcasts() {
1233            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1234        }
1235
1236        public ArrayList<String> get(int userId, String packageName) {
1237            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1238            return packages.get(packageName);
1239        }
1240
1241        public void put(int userId, String packageName, ArrayList<String> components) {
1242            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1243            packages.put(packageName, components);
1244        }
1245
1246        public void remove(int userId, String packageName) {
1247            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1248            if (packages != null) {
1249                packages.remove(packageName);
1250            }
1251        }
1252
1253        public void remove(int userId) {
1254            mUidMap.remove(userId);
1255        }
1256
1257        public int userIdCount() {
1258            return mUidMap.size();
1259        }
1260
1261        public int userIdAt(int n) {
1262            return mUidMap.keyAt(n);
1263        }
1264
1265        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1266            return mUidMap.get(userId);
1267        }
1268
1269        public int size() {
1270            // total number of pending broadcast entries across all userIds
1271            int num = 0;
1272            for (int i = 0; i< mUidMap.size(); i++) {
1273                num += mUidMap.valueAt(i).size();
1274            }
1275            return num;
1276        }
1277
1278        public void clear() {
1279            mUidMap.clear();
1280        }
1281
1282        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1283            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1284            if (map == null) {
1285                map = new ArrayMap<String, ArrayList<String>>();
1286                mUidMap.put(userId, map);
1287            }
1288            return map;
1289        }
1290    }
1291    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1292
1293    // Service Connection to remote media container service to copy
1294    // package uri's from external media onto secure containers
1295    // or internal storage.
1296    private IMediaContainerService mContainerService = null;
1297
1298    static final int SEND_PENDING_BROADCAST = 1;
1299    static final int MCS_BOUND = 3;
1300    static final int END_COPY = 4;
1301    static final int INIT_COPY = 5;
1302    static final int MCS_UNBIND = 6;
1303    static final int START_CLEANING_PACKAGE = 7;
1304    static final int FIND_INSTALL_LOC = 8;
1305    static final int POST_INSTALL = 9;
1306    static final int MCS_RECONNECT = 10;
1307    static final int MCS_GIVE_UP = 11;
1308    static final int WRITE_SETTINGS = 13;
1309    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1310    static final int PACKAGE_VERIFIED = 15;
1311    static final int CHECK_PENDING_VERIFICATION = 16;
1312    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1313    static final int INTENT_FILTER_VERIFIED = 18;
1314    static final int WRITE_PACKAGE_LIST = 19;
1315    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1316
1317    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1318
1319    // Delay time in millisecs
1320    static final int BROADCAST_DELAY = 10 * 1000;
1321
1322    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1323            2 * 60 * 60 * 1000L; /* two hours */
1324
1325    static UserManagerService sUserManager;
1326
1327    // Stores a list of users whose package restrictions file needs to be updated
1328    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1329
1330    final private DefaultContainerConnection mDefContainerConn =
1331            new DefaultContainerConnection();
1332    class DefaultContainerConnection implements ServiceConnection {
1333        public void onServiceConnected(ComponentName name, IBinder service) {
1334            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1335            final IMediaContainerService imcs = IMediaContainerService.Stub
1336                    .asInterface(Binder.allowBlocking(service));
1337            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1338        }
1339
1340        public void onServiceDisconnected(ComponentName name) {
1341            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1342        }
1343    }
1344
1345    // Recordkeeping of restore-after-install operations that are currently in flight
1346    // between the Package Manager and the Backup Manager
1347    static class PostInstallData {
1348        public InstallArgs args;
1349        public PackageInstalledInfo res;
1350
1351        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1352            args = _a;
1353            res = _r;
1354        }
1355    }
1356
1357    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1358    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1359
1360    // XML tags for backup/restore of various bits of state
1361    private static final String TAG_PREFERRED_BACKUP = "pa";
1362    private static final String TAG_DEFAULT_APPS = "da";
1363    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1364
1365    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1366    private static final String TAG_ALL_GRANTS = "rt-grants";
1367    private static final String TAG_GRANT = "grant";
1368    private static final String ATTR_PACKAGE_NAME = "pkg";
1369
1370    private static final String TAG_PERMISSION = "perm";
1371    private static final String ATTR_PERMISSION_NAME = "name";
1372    private static final String ATTR_IS_GRANTED = "g";
1373    private static final String ATTR_USER_SET = "set";
1374    private static final String ATTR_USER_FIXED = "fixed";
1375    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1376
1377    // System/policy permission grants are not backed up
1378    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1379            FLAG_PERMISSION_POLICY_FIXED
1380            | FLAG_PERMISSION_SYSTEM_FIXED
1381            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1382
1383    // And we back up these user-adjusted states
1384    private static final int USER_RUNTIME_GRANT_MASK =
1385            FLAG_PERMISSION_USER_SET
1386            | FLAG_PERMISSION_USER_FIXED
1387            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1388
1389    final @Nullable String mRequiredVerifierPackage;
1390    final @NonNull String mRequiredInstallerPackage;
1391    final @NonNull String mRequiredUninstallerPackage;
1392    final @Nullable String mSetupWizardPackage;
1393    final @Nullable String mStorageManagerPackage;
1394    final @NonNull String mServicesSystemSharedLibraryPackageName;
1395    final @NonNull String mSharedSystemSharedLibraryPackageName;
1396
1397    private final PackageUsage mPackageUsage = new PackageUsage();
1398    private final CompilerStats mCompilerStats = new CompilerStats();
1399
1400    class PackageHandler extends Handler {
1401        private boolean mBound = false;
1402        final ArrayList<HandlerParams> mPendingInstalls =
1403            new ArrayList<HandlerParams>();
1404
1405        private boolean connectToService() {
1406            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1407                    " DefaultContainerService");
1408            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1409            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1410            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1411                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1412                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1413                mBound = true;
1414                return true;
1415            }
1416            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1417            return false;
1418        }
1419
1420        private void disconnectService() {
1421            mContainerService = null;
1422            mBound = false;
1423            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1424            mContext.unbindService(mDefContainerConn);
1425            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1426        }
1427
1428        PackageHandler(Looper looper) {
1429            super(looper);
1430        }
1431
1432        public void handleMessage(Message msg) {
1433            try {
1434                doHandleMessage(msg);
1435            } finally {
1436                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1437            }
1438        }
1439
1440        void doHandleMessage(Message msg) {
1441            switch (msg.what) {
1442                case INIT_COPY: {
1443                    HandlerParams params = (HandlerParams) msg.obj;
1444                    int idx = mPendingInstalls.size();
1445                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1446                    // If a bind was already initiated we dont really
1447                    // need to do anything. The pending install
1448                    // will be processed later on.
1449                    if (!mBound) {
1450                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1451                                System.identityHashCode(mHandler));
1452                        // If this is the only one pending we might
1453                        // have to bind to the service again.
1454                        if (!connectToService()) {
1455                            Slog.e(TAG, "Failed to bind to media container service");
1456                            params.serviceError();
1457                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1458                                    System.identityHashCode(mHandler));
1459                            if (params.traceMethod != null) {
1460                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1461                                        params.traceCookie);
1462                            }
1463                            return;
1464                        } else {
1465                            // Once we bind to the service, the first
1466                            // pending request will be processed.
1467                            mPendingInstalls.add(idx, params);
1468                        }
1469                    } else {
1470                        mPendingInstalls.add(idx, params);
1471                        // Already bound to the service. Just make
1472                        // sure we trigger off processing the first request.
1473                        if (idx == 0) {
1474                            mHandler.sendEmptyMessage(MCS_BOUND);
1475                        }
1476                    }
1477                    break;
1478                }
1479                case MCS_BOUND: {
1480                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1481                    if (msg.obj != null) {
1482                        mContainerService = (IMediaContainerService) msg.obj;
1483                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1484                                System.identityHashCode(mHandler));
1485                    }
1486                    if (mContainerService == null) {
1487                        if (!mBound) {
1488                            // Something seriously wrong since we are not bound and we are not
1489                            // waiting for connection. Bail out.
1490                            Slog.e(TAG, "Cannot bind to media container service");
1491                            for (HandlerParams params : mPendingInstalls) {
1492                                // Indicate service bind error
1493                                params.serviceError();
1494                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1495                                        System.identityHashCode(params));
1496                                if (params.traceMethod != null) {
1497                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1498                                            params.traceMethod, params.traceCookie);
1499                                }
1500                                return;
1501                            }
1502                            mPendingInstalls.clear();
1503                        } else {
1504                            Slog.w(TAG, "Waiting to connect to media container service");
1505                        }
1506                    } else if (mPendingInstalls.size() > 0) {
1507                        HandlerParams params = mPendingInstalls.get(0);
1508                        if (params != null) {
1509                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1510                                    System.identityHashCode(params));
1511                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1512                            if (params.startCopy()) {
1513                                // We are done...  look for more work or to
1514                                // go idle.
1515                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1516                                        "Checking for more work or unbind...");
1517                                // Delete pending install
1518                                if (mPendingInstalls.size() > 0) {
1519                                    mPendingInstalls.remove(0);
1520                                }
1521                                if (mPendingInstalls.size() == 0) {
1522                                    if (mBound) {
1523                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1524                                                "Posting delayed MCS_UNBIND");
1525                                        removeMessages(MCS_UNBIND);
1526                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1527                                        // Unbind after a little delay, to avoid
1528                                        // continual thrashing.
1529                                        sendMessageDelayed(ubmsg, 10000);
1530                                    }
1531                                } else {
1532                                    // There are more pending requests in queue.
1533                                    // Just post MCS_BOUND message to trigger processing
1534                                    // of next pending install.
1535                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1536                                            "Posting MCS_BOUND for next work");
1537                                    mHandler.sendEmptyMessage(MCS_BOUND);
1538                                }
1539                            }
1540                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1541                        }
1542                    } else {
1543                        // Should never happen ideally.
1544                        Slog.w(TAG, "Empty queue");
1545                    }
1546                    break;
1547                }
1548                case MCS_RECONNECT: {
1549                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1550                    if (mPendingInstalls.size() > 0) {
1551                        if (mBound) {
1552                            disconnectService();
1553                        }
1554                        if (!connectToService()) {
1555                            Slog.e(TAG, "Failed to bind to media container service");
1556                            for (HandlerParams params : mPendingInstalls) {
1557                                // Indicate service bind error
1558                                params.serviceError();
1559                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1560                                        System.identityHashCode(params));
1561                            }
1562                            mPendingInstalls.clear();
1563                        }
1564                    }
1565                    break;
1566                }
1567                case MCS_UNBIND: {
1568                    // If there is no actual work left, then time to unbind.
1569                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1570
1571                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1572                        if (mBound) {
1573                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1574
1575                            disconnectService();
1576                        }
1577                    } else if (mPendingInstalls.size() > 0) {
1578                        // There are more pending requests in queue.
1579                        // Just post MCS_BOUND message to trigger processing
1580                        // of next pending install.
1581                        mHandler.sendEmptyMessage(MCS_BOUND);
1582                    }
1583
1584                    break;
1585                }
1586                case MCS_GIVE_UP: {
1587                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1588                    HandlerParams params = mPendingInstalls.remove(0);
1589                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1590                            System.identityHashCode(params));
1591                    break;
1592                }
1593                case SEND_PENDING_BROADCAST: {
1594                    String packages[];
1595                    ArrayList<String> components[];
1596                    int size = 0;
1597                    int uids[];
1598                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1599                    synchronized (mPackages) {
1600                        if (mPendingBroadcasts == null) {
1601                            return;
1602                        }
1603                        size = mPendingBroadcasts.size();
1604                        if (size <= 0) {
1605                            // Nothing to be done. Just return
1606                            return;
1607                        }
1608                        packages = new String[size];
1609                        components = new ArrayList[size];
1610                        uids = new int[size];
1611                        int i = 0;  // filling out the above arrays
1612
1613                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1614                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1615                            Iterator<Map.Entry<String, ArrayList<String>>> it
1616                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1617                                            .entrySet().iterator();
1618                            while (it.hasNext() && i < size) {
1619                                Map.Entry<String, ArrayList<String>> ent = it.next();
1620                                packages[i] = ent.getKey();
1621                                components[i] = ent.getValue();
1622                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1623                                uids[i] = (ps != null)
1624                                        ? UserHandle.getUid(packageUserId, ps.appId)
1625                                        : -1;
1626                                i++;
1627                            }
1628                        }
1629                        size = i;
1630                        mPendingBroadcasts.clear();
1631                    }
1632                    // Send broadcasts
1633                    for (int i = 0; i < size; i++) {
1634                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1635                    }
1636                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1637                    break;
1638                }
1639                case START_CLEANING_PACKAGE: {
1640                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1641                    final String packageName = (String)msg.obj;
1642                    final int userId = msg.arg1;
1643                    final boolean andCode = msg.arg2 != 0;
1644                    synchronized (mPackages) {
1645                        if (userId == UserHandle.USER_ALL) {
1646                            int[] users = sUserManager.getUserIds();
1647                            for (int user : users) {
1648                                mSettings.addPackageToCleanLPw(
1649                                        new PackageCleanItem(user, packageName, andCode));
1650                            }
1651                        } else {
1652                            mSettings.addPackageToCleanLPw(
1653                                    new PackageCleanItem(userId, packageName, andCode));
1654                        }
1655                    }
1656                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1657                    startCleaningPackages();
1658                } break;
1659                case POST_INSTALL: {
1660                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1661
1662                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1663                    final boolean didRestore = (msg.arg2 != 0);
1664                    mRunningInstalls.delete(msg.arg1);
1665
1666                    if (data != null) {
1667                        InstallArgs args = data.args;
1668                        PackageInstalledInfo parentRes = data.res;
1669
1670                        final boolean grantPermissions = (args.installFlags
1671                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1672                        final boolean killApp = (args.installFlags
1673                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1674                        final boolean virtualPreload = ((args.installFlags
1675                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1676                        final String[] grantedPermissions = args.installGrantPermissions;
1677
1678                        // Handle the parent package
1679                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1680                                virtualPreload, grantedPermissions, didRestore,
1681                                args.installerPackageName, args.observer);
1682
1683                        // Handle the child packages
1684                        final int childCount = (parentRes.addedChildPackages != null)
1685                                ? parentRes.addedChildPackages.size() : 0;
1686                        for (int i = 0; i < childCount; i++) {
1687                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1688                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1689                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1690                                    args.installerPackageName, args.observer);
1691                        }
1692
1693                        // Log tracing if needed
1694                        if (args.traceMethod != null) {
1695                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1696                                    args.traceCookie);
1697                        }
1698                    } else {
1699                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1700                    }
1701
1702                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1703                } break;
1704                case WRITE_SETTINGS: {
1705                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1706                    synchronized (mPackages) {
1707                        removeMessages(WRITE_SETTINGS);
1708                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1709                        mSettings.writeLPr();
1710                        mDirtyUsers.clear();
1711                    }
1712                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1713                } break;
1714                case WRITE_PACKAGE_RESTRICTIONS: {
1715                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1716                    synchronized (mPackages) {
1717                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1718                        for (int userId : mDirtyUsers) {
1719                            mSettings.writePackageRestrictionsLPr(userId);
1720                        }
1721                        mDirtyUsers.clear();
1722                    }
1723                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1724                } break;
1725                case WRITE_PACKAGE_LIST: {
1726                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1727                    synchronized (mPackages) {
1728                        removeMessages(WRITE_PACKAGE_LIST);
1729                        mSettings.writePackageListLPr(msg.arg1);
1730                    }
1731                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1732                } break;
1733                case CHECK_PENDING_VERIFICATION: {
1734                    final int verificationId = msg.arg1;
1735                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1736
1737                    if ((state != null) && !state.timeoutExtended()) {
1738                        final InstallArgs args = state.getInstallArgs();
1739                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1740
1741                        Slog.i(TAG, "Verification timed out for " + originUri);
1742                        mPendingVerification.remove(verificationId);
1743
1744                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1745
1746                        final UserHandle user = args.getUser();
1747                        if (getDefaultVerificationResponse(user)
1748                                == PackageManager.VERIFICATION_ALLOW) {
1749                            Slog.i(TAG, "Continuing with installation of " + originUri);
1750                            state.setVerifierResponse(Binder.getCallingUid(),
1751                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1752                            broadcastPackageVerified(verificationId, originUri,
1753                                    PackageManager.VERIFICATION_ALLOW, user);
1754                            try {
1755                                ret = args.copyApk(mContainerService, true);
1756                            } catch (RemoteException e) {
1757                                Slog.e(TAG, "Could not contact the ContainerService");
1758                            }
1759                        } else {
1760                            broadcastPackageVerified(verificationId, originUri,
1761                                    PackageManager.VERIFICATION_REJECT, user);
1762                        }
1763
1764                        Trace.asyncTraceEnd(
1765                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1766
1767                        processPendingInstall(args, ret);
1768                        mHandler.sendEmptyMessage(MCS_UNBIND);
1769                    }
1770                    break;
1771                }
1772                case PACKAGE_VERIFIED: {
1773                    final int verificationId = msg.arg1;
1774
1775                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1776                    if (state == null) {
1777                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1778                        break;
1779                    }
1780
1781                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1782
1783                    state.setVerifierResponse(response.callerUid, response.code);
1784
1785                    if (state.isVerificationComplete()) {
1786                        mPendingVerification.remove(verificationId);
1787
1788                        final InstallArgs args = state.getInstallArgs();
1789                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1790
1791                        int ret;
1792                        if (state.isInstallAllowed()) {
1793                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1794                            broadcastPackageVerified(verificationId, originUri,
1795                                    response.code, state.getInstallArgs().getUser());
1796                            try {
1797                                ret = args.copyApk(mContainerService, true);
1798                            } catch (RemoteException e) {
1799                                Slog.e(TAG, "Could not contact the ContainerService");
1800                            }
1801                        } else {
1802                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1803                        }
1804
1805                        Trace.asyncTraceEnd(
1806                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1807
1808                        processPendingInstall(args, ret);
1809                        mHandler.sendEmptyMessage(MCS_UNBIND);
1810                    }
1811
1812                    break;
1813                }
1814                case START_INTENT_FILTER_VERIFICATIONS: {
1815                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1816                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1817                            params.replacing, params.pkg);
1818                    break;
1819                }
1820                case INTENT_FILTER_VERIFIED: {
1821                    final int verificationId = msg.arg1;
1822
1823                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1824                            verificationId);
1825                    if (state == null) {
1826                        Slog.w(TAG, "Invalid IntentFilter verification token "
1827                                + verificationId + " received");
1828                        break;
1829                    }
1830
1831                    final int userId = state.getUserId();
1832
1833                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1834                            "Processing IntentFilter verification with token:"
1835                            + verificationId + " and userId:" + userId);
1836
1837                    final IntentFilterVerificationResponse response =
1838                            (IntentFilterVerificationResponse) msg.obj;
1839
1840                    state.setVerifierResponse(response.callerUid, response.code);
1841
1842                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1843                            "IntentFilter verification with token:" + verificationId
1844                            + " and userId:" + userId
1845                            + " is settings verifier response with response code:"
1846                            + response.code);
1847
1848                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1849                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1850                                + response.getFailedDomainsString());
1851                    }
1852
1853                    if (state.isVerificationComplete()) {
1854                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1855                    } else {
1856                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1857                                "IntentFilter verification with token:" + verificationId
1858                                + " was not said to be complete");
1859                    }
1860
1861                    break;
1862                }
1863                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1864                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1865                            mInstantAppResolverConnection,
1866                            (InstantAppRequest) msg.obj,
1867                            mInstantAppInstallerActivity,
1868                            mHandler);
1869                }
1870            }
1871        }
1872    }
1873
1874    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1875        @Override
1876        public void onGidsChanged(int appId, int userId) {
1877            mHandler.post(new Runnable() {
1878                @Override
1879                public void run() {
1880                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1881                }
1882            });
1883        }
1884        @Override
1885        public void onPermissionGranted(int uid, int userId) {
1886            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1887
1888            // Not critical; if this is lost, the application has to request again.
1889            synchronized (mPackages) {
1890                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1891            }
1892        }
1893        @Override
1894        public void onInstallPermissionGranted() {
1895            synchronized (mPackages) {
1896                scheduleWriteSettingsLocked();
1897            }
1898        }
1899        @Override
1900        public void onPermissionRevoked(int uid, int userId) {
1901            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1902
1903            synchronized (mPackages) {
1904                // Critical; after this call the application should never have the permission
1905                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1906            }
1907
1908            final int appId = UserHandle.getAppId(uid);
1909            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1910        }
1911        @Override
1912        public void onInstallPermissionRevoked() {
1913            synchronized (mPackages) {
1914                scheduleWriteSettingsLocked();
1915            }
1916        }
1917        @Override
1918        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1919            synchronized (mPackages) {
1920                for (int userId : updatedUserIds) {
1921                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1922                }
1923            }
1924        }
1925        @Override
1926        public void onInstallPermissionUpdated() {
1927            synchronized (mPackages) {
1928                scheduleWriteSettingsLocked();
1929            }
1930        }
1931        @Override
1932        public void onPermissionRemoved() {
1933            synchronized (mPackages) {
1934                mSettings.writeLPr();
1935            }
1936        }
1937    };
1938
1939    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1940            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1941            boolean launchedForRestore, String installerPackage,
1942            IPackageInstallObserver2 installObserver) {
1943        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1944            // Send the removed broadcasts
1945            if (res.removedInfo != null) {
1946                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1947            }
1948
1949            // Now that we successfully installed the package, grant runtime
1950            // permissions if requested before broadcasting the install. Also
1951            // for legacy apps in permission review mode we clear the permission
1952            // review flag which is used to emulate runtime permissions for
1953            // legacy apps.
1954            if (grantPermissions) {
1955                final int callingUid = Binder.getCallingUid();
1956                mPermissionManager.grantRequestedRuntimePermissions(
1957                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1958                        mPermissionCallback);
1959            }
1960
1961            final boolean update = res.removedInfo != null
1962                    && res.removedInfo.removedPackage != null;
1963            final String installerPackageName =
1964                    res.installerPackageName != null
1965                            ? res.installerPackageName
1966                            : res.removedInfo != null
1967                                    ? res.removedInfo.installerPackageName
1968                                    : null;
1969
1970            // If this is the first time we have child packages for a disabled privileged
1971            // app that had no children, we grant requested runtime permissions to the new
1972            // children if the parent on the system image had them already granted.
1973            if (res.pkg.parentPackage != null) {
1974                final int callingUid = Binder.getCallingUid();
1975                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1976                        res.pkg, callingUid, mPermissionCallback);
1977            }
1978
1979            synchronized (mPackages) {
1980                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1981            }
1982
1983            final String packageName = res.pkg.applicationInfo.packageName;
1984
1985            // Determine the set of users who are adding this package for
1986            // the first time vs. those who are seeing an update.
1987            int[] firstUserIds = EMPTY_INT_ARRAY;
1988            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1989            int[] updateUserIds = EMPTY_INT_ARRAY;
1990            int[] instantUserIds = EMPTY_INT_ARRAY;
1991            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1992            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1993            for (int newUser : res.newUsers) {
1994                final boolean isInstantApp = ps.getInstantApp(newUser);
1995                if (allNewUsers) {
1996                    if (isInstantApp) {
1997                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1998                    } else {
1999                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2000                    }
2001                    continue;
2002                }
2003                boolean isNew = true;
2004                for (int origUser : res.origUsers) {
2005                    if (origUser == newUser) {
2006                        isNew = false;
2007                        break;
2008                    }
2009                }
2010                if (isNew) {
2011                    if (isInstantApp) {
2012                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2013                    } else {
2014                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2015                    }
2016                } else {
2017                    if (isInstantApp) {
2018                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2019                    } else {
2020                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2021                    }
2022                }
2023            }
2024
2025            // Send installed broadcasts if the package is not a static shared lib.
2026            if (res.pkg.staticSharedLibName == null) {
2027                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2028
2029                // Send added for users that see the package for the first time
2030                // sendPackageAddedForNewUsers also deals with system apps
2031                int appId = UserHandle.getAppId(res.uid);
2032                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2033                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2034                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2035
2036                // Send added for users that don't see the package for the first time
2037                Bundle extras = new Bundle(1);
2038                extras.putInt(Intent.EXTRA_UID, res.uid);
2039                if (update) {
2040                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2041                }
2042                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2043                        extras, 0 /*flags*/,
2044                        null /*targetPackage*/, null /*finishedReceiver*/,
2045                        updateUserIds, instantUserIds);
2046                if (installerPackageName != null) {
2047                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2048                            extras, 0 /*flags*/,
2049                            installerPackageName, null /*finishedReceiver*/,
2050                            updateUserIds, instantUserIds);
2051                }
2052
2053                // Send replaced for users that don't see the package for the first time
2054                if (update) {
2055                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2056                            packageName, extras, 0 /*flags*/,
2057                            null /*targetPackage*/, null /*finishedReceiver*/,
2058                            updateUserIds, instantUserIds);
2059                    if (installerPackageName != null) {
2060                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2061                                extras, 0 /*flags*/,
2062                                installerPackageName, null /*finishedReceiver*/,
2063                                updateUserIds, instantUserIds);
2064                    }
2065                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2066                            null /*package*/, null /*extras*/, 0 /*flags*/,
2067                            packageName /*targetPackage*/,
2068                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2069                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2070                    // First-install and we did a restore, so we're responsible for the
2071                    // first-launch broadcast.
2072                    if (DEBUG_BACKUP) {
2073                        Slog.i(TAG, "Post-restore of " + packageName
2074                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2075                    }
2076                    sendFirstLaunchBroadcast(packageName, installerPackage,
2077                            firstUserIds, firstInstantUserIds);
2078                }
2079
2080                // Send broadcast package appeared if forward locked/external for all users
2081                // treat asec-hosted packages like removable media on upgrade
2082                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2083                    if (DEBUG_INSTALL) {
2084                        Slog.i(TAG, "upgrading pkg " + res.pkg
2085                                + " is ASEC-hosted -> AVAILABLE");
2086                    }
2087                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2088                    ArrayList<String> pkgList = new ArrayList<>(1);
2089                    pkgList.add(packageName);
2090                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2091                }
2092            }
2093
2094            // Work that needs to happen on first install within each user
2095            if (firstUserIds != null && firstUserIds.length > 0) {
2096                synchronized (mPackages) {
2097                    for (int userId : firstUserIds) {
2098                        // If this app is a browser and it's newly-installed for some
2099                        // users, clear any default-browser state in those users. The
2100                        // app's nature doesn't depend on the user, so we can just check
2101                        // its browser nature in any user and generalize.
2102                        if (packageIsBrowser(packageName, userId)) {
2103                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2104                        }
2105
2106                        // We may also need to apply pending (restored) runtime
2107                        // permission grants within these users.
2108                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2109                    }
2110                }
2111            }
2112
2113            if (allNewUsers && !update) {
2114                notifyPackageAdded(packageName);
2115            }
2116
2117            // Log current value of "unknown sources" setting
2118            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2119                    getUnknownSourcesSettings());
2120
2121            // Remove the replaced package's older resources safely now
2122            // We delete after a gc for applications  on sdcard.
2123            if (res.removedInfo != null && res.removedInfo.args != null) {
2124                Runtime.getRuntime().gc();
2125                synchronized (mInstallLock) {
2126                    res.removedInfo.args.doPostDeleteLI(true);
2127                }
2128            } else {
2129                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2130                // and not block here.
2131                VMRuntime.getRuntime().requestConcurrentGC();
2132            }
2133
2134            // Notify DexManager that the package was installed for new users.
2135            // The updated users should already be indexed and the package code paths
2136            // should not change.
2137            // Don't notify the manager for ephemeral apps as they are not expected to
2138            // survive long enough to benefit of background optimizations.
2139            for (int userId : firstUserIds) {
2140                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2141                // There's a race currently where some install events may interleave with an uninstall.
2142                // This can lead to package info being null (b/36642664).
2143                if (info != null) {
2144                    mDexManager.notifyPackageInstalled(info, userId);
2145                }
2146            }
2147        }
2148
2149        // If someone is watching installs - notify them
2150        if (installObserver != null) {
2151            try {
2152                Bundle extras = extrasForInstallResult(res);
2153                installObserver.onPackageInstalled(res.name, res.returnCode,
2154                        res.returnMsg, extras);
2155            } catch (RemoteException e) {
2156                Slog.i(TAG, "Observer no longer exists.");
2157            }
2158        }
2159    }
2160
2161    private StorageEventListener mStorageListener = new StorageEventListener() {
2162        @Override
2163        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2164            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2165                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2166                    final String volumeUuid = vol.getFsUuid();
2167
2168                    // Clean up any users or apps that were removed or recreated
2169                    // while this volume was missing
2170                    sUserManager.reconcileUsers(volumeUuid);
2171                    reconcileApps(volumeUuid);
2172
2173                    // Clean up any install sessions that expired or were
2174                    // cancelled while this volume was missing
2175                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2176
2177                    loadPrivatePackages(vol);
2178
2179                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2180                    unloadPrivatePackages(vol);
2181                }
2182            }
2183        }
2184
2185        @Override
2186        public void onVolumeForgotten(String fsUuid) {
2187            if (TextUtils.isEmpty(fsUuid)) {
2188                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2189                return;
2190            }
2191
2192            // Remove any apps installed on the forgotten volume
2193            synchronized (mPackages) {
2194                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2195                for (PackageSetting ps : packages) {
2196                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2197                    deletePackageVersioned(new VersionedPackage(ps.name,
2198                            PackageManager.VERSION_CODE_HIGHEST),
2199                            new LegacyPackageDeleteObserver(null).getBinder(),
2200                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2201                    // Try very hard to release any references to this package
2202                    // so we don't risk the system server being killed due to
2203                    // open FDs
2204                    AttributeCache.instance().removePackage(ps.name);
2205                }
2206
2207                mSettings.onVolumeForgotten(fsUuid);
2208                mSettings.writeLPr();
2209            }
2210        }
2211    };
2212
2213    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2214        Bundle extras = null;
2215        switch (res.returnCode) {
2216            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2217                extras = new Bundle();
2218                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2219                        res.origPermission);
2220                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2221                        res.origPackage);
2222                break;
2223            }
2224            case PackageManager.INSTALL_SUCCEEDED: {
2225                extras = new Bundle();
2226                extras.putBoolean(Intent.EXTRA_REPLACING,
2227                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2228                break;
2229            }
2230        }
2231        return extras;
2232    }
2233
2234    void scheduleWriteSettingsLocked() {
2235        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2236            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2237        }
2238    }
2239
2240    void scheduleWritePackageListLocked(int userId) {
2241        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2242            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2243            msg.arg1 = userId;
2244            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2245        }
2246    }
2247
2248    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2249        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2250        scheduleWritePackageRestrictionsLocked(userId);
2251    }
2252
2253    void scheduleWritePackageRestrictionsLocked(int userId) {
2254        final int[] userIds = (userId == UserHandle.USER_ALL)
2255                ? sUserManager.getUserIds() : new int[]{userId};
2256        for (int nextUserId : userIds) {
2257            if (!sUserManager.exists(nextUserId)) return;
2258            mDirtyUsers.add(nextUserId);
2259            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2260                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2261            }
2262        }
2263    }
2264
2265    public static PackageManagerService main(Context context, Installer installer,
2266            boolean factoryTest, boolean onlyCore) {
2267        // Self-check for initial settings.
2268        PackageManagerServiceCompilerMapping.checkProperties();
2269
2270        PackageManagerService m = new PackageManagerService(context, installer,
2271                factoryTest, onlyCore);
2272        m.enableSystemUserPackages();
2273        ServiceManager.addService("package", m);
2274        final PackageManagerNative pmn = m.new PackageManagerNative();
2275        ServiceManager.addService("package_native", pmn);
2276        return m;
2277    }
2278
2279    private void enableSystemUserPackages() {
2280        if (!UserManager.isSplitSystemUser()) {
2281            return;
2282        }
2283        // For system user, enable apps based on the following conditions:
2284        // - app is whitelisted or belong to one of these groups:
2285        //   -- system app which has no launcher icons
2286        //   -- system app which has INTERACT_ACROSS_USERS permission
2287        //   -- system IME app
2288        // - app is not in the blacklist
2289        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2290        Set<String> enableApps = new ArraySet<>();
2291        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2292                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2293                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2294        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2295        enableApps.addAll(wlApps);
2296        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2297                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2298        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2299        enableApps.removeAll(blApps);
2300        Log.i(TAG, "Applications installed for system user: " + enableApps);
2301        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2302                UserHandle.SYSTEM);
2303        final int allAppsSize = allAps.size();
2304        synchronized (mPackages) {
2305            for (int i = 0; i < allAppsSize; i++) {
2306                String pName = allAps.get(i);
2307                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2308                // Should not happen, but we shouldn't be failing if it does
2309                if (pkgSetting == null) {
2310                    continue;
2311                }
2312                boolean install = enableApps.contains(pName);
2313                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2314                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2315                            + " for system user");
2316                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2317                }
2318            }
2319            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2320        }
2321    }
2322
2323    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2324        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2325                Context.DISPLAY_SERVICE);
2326        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2327    }
2328
2329    /**
2330     * Requests that files preopted on a secondary system partition be copied to the data partition
2331     * if possible.  Note that the actual copying of the files is accomplished by init for security
2332     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2333     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2334     */
2335    private static void requestCopyPreoptedFiles() {
2336        final int WAIT_TIME_MS = 100;
2337        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2338        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2339            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2340            // We will wait for up to 100 seconds.
2341            final long timeStart = SystemClock.uptimeMillis();
2342            final long timeEnd = timeStart + 100 * 1000;
2343            long timeNow = timeStart;
2344            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2345                try {
2346                    Thread.sleep(WAIT_TIME_MS);
2347                } catch (InterruptedException e) {
2348                    // Do nothing
2349                }
2350                timeNow = SystemClock.uptimeMillis();
2351                if (timeNow > timeEnd) {
2352                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2353                    Slog.wtf(TAG, "cppreopt did not finish!");
2354                    break;
2355                }
2356            }
2357
2358            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2359        }
2360    }
2361
2362    public PackageManagerService(Context context, Installer installer,
2363            boolean factoryTest, boolean onlyCore) {
2364        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2365        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2366        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2367                SystemClock.uptimeMillis());
2368
2369        if (mSdkVersion <= 0) {
2370            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2371        }
2372
2373        mContext = context;
2374
2375        mFactoryTest = factoryTest;
2376        mOnlyCore = onlyCore;
2377        mMetrics = new DisplayMetrics();
2378        mInstaller = installer;
2379
2380        // Create sub-components that provide services / data. Order here is important.
2381        synchronized (mInstallLock) {
2382        synchronized (mPackages) {
2383            // Expose private service for system components to use.
2384            LocalServices.addService(
2385                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2386            sUserManager = new UserManagerService(context, this,
2387                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2388            mPermissionManager = PermissionManagerService.create(context,
2389                    new DefaultPermissionGrantedCallback() {
2390                        @Override
2391                        public void onDefaultRuntimePermissionsGranted(int userId) {
2392                            synchronized(mPackages) {
2393                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2394                            }
2395                        }
2396                    }, mPackages /*externalLock*/);
2397            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2398            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2399        }
2400        }
2401        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2410                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2411        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2412                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2413        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2414                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2415
2416        String separateProcesses = SystemProperties.get("debug.separate_processes");
2417        if (separateProcesses != null && separateProcesses.length() > 0) {
2418            if ("*".equals(separateProcesses)) {
2419                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2420                mSeparateProcesses = null;
2421                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2422            } else {
2423                mDefParseFlags = 0;
2424                mSeparateProcesses = separateProcesses.split(",");
2425                Slog.w(TAG, "Running with debug.separate_processes: "
2426                        + separateProcesses);
2427            }
2428        } else {
2429            mDefParseFlags = 0;
2430            mSeparateProcesses = null;
2431        }
2432
2433        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2434                "*dexopt*");
2435        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2436                installer, mInstallLock);
2437        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2438                dexManagerListener);
2439        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2440        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2441
2442        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2443                FgThread.get().getLooper());
2444
2445        getDefaultDisplayMetrics(context, mMetrics);
2446
2447        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2448        SystemConfig systemConfig = SystemConfig.getInstance();
2449        mAvailableFeatures = systemConfig.getAvailableFeatures();
2450        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2451
2452        mProtectedPackages = new ProtectedPackages(mContext);
2453
2454        synchronized (mInstallLock) {
2455        // writer
2456        synchronized (mPackages) {
2457            mHandlerThread = new ServiceThread(TAG,
2458                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2459            mHandlerThread.start();
2460            mHandler = new PackageHandler(mHandlerThread.getLooper());
2461            mProcessLoggingHandler = new ProcessLoggingHandler();
2462            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2463            mInstantAppRegistry = new InstantAppRegistry(this);
2464
2465            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2466            final int builtInLibCount = libConfig.size();
2467            for (int i = 0; i < builtInLibCount; i++) {
2468                String name = libConfig.keyAt(i);
2469                String path = libConfig.valueAt(i);
2470                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2471                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2472            }
2473
2474            SELinuxMMAC.readInstallPolicy();
2475
2476            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2477            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2478            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2479
2480            // Clean up orphaned packages for which the code path doesn't exist
2481            // and they are an update to a system app - caused by bug/32321269
2482            final int packageSettingCount = mSettings.mPackages.size();
2483            for (int i = packageSettingCount - 1; i >= 0; i--) {
2484                PackageSetting ps = mSettings.mPackages.valueAt(i);
2485                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2486                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2487                    mSettings.mPackages.removeAt(i);
2488                    mSettings.enableSystemPackageLPw(ps.name);
2489                }
2490            }
2491
2492            if (mFirstBoot) {
2493                requestCopyPreoptedFiles();
2494            }
2495
2496            String customResolverActivity = Resources.getSystem().getString(
2497                    R.string.config_customResolverActivity);
2498            if (TextUtils.isEmpty(customResolverActivity)) {
2499                customResolverActivity = null;
2500            } else {
2501                mCustomResolverComponentName = ComponentName.unflattenFromString(
2502                        customResolverActivity);
2503            }
2504
2505            long startTime = SystemClock.uptimeMillis();
2506
2507            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2508                    startTime);
2509
2510            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2511            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2512
2513            if (bootClassPath == null) {
2514                Slog.w(TAG, "No BOOTCLASSPATH found!");
2515            }
2516
2517            if (systemServerClassPath == null) {
2518                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2519            }
2520
2521            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2522
2523            final VersionInfo ver = mSettings.getInternalVersion();
2524            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2525            if (mIsUpgrade) {
2526                logCriticalInfo(Log.INFO,
2527                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2528            }
2529
2530            // when upgrading from pre-M, promote system app permissions from install to runtime
2531            mPromoteSystemApps =
2532                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2533
2534            // When upgrading from pre-N, we need to handle package extraction like first boot,
2535            // as there is no profiling data available.
2536            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2537
2538            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2539
2540            // save off the names of pre-existing system packages prior to scanning; we don't
2541            // want to automatically grant runtime permissions for new system apps
2542            if (mPromoteSystemApps) {
2543                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2544                while (pkgSettingIter.hasNext()) {
2545                    PackageSetting ps = pkgSettingIter.next();
2546                    if (isSystemApp(ps)) {
2547                        mExistingSystemPackages.add(ps.name);
2548                    }
2549                }
2550            }
2551
2552            mCacheDir = preparePackageParserCache(mIsUpgrade);
2553
2554            // Set flag to monitor and not change apk file paths when
2555            // scanning install directories.
2556            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2557
2558            if (mIsUpgrade || mFirstBoot) {
2559                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2560            }
2561
2562            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2563            // For security and version matching reason, only consider
2564            // overlay packages if they reside in the right directory.
2565            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2566                    mDefParseFlags
2567                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2568                    scanFlags
2569                    | SCAN_AS_SYSTEM
2570                    | SCAN_AS_VENDOR,
2571                    0);
2572            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2573                    mDefParseFlags
2574                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2575                    scanFlags
2576                    | SCAN_AS_SYSTEM
2577                    | SCAN_AS_PRODUCT,
2578                    0);
2579
2580            mParallelPackageParserCallback.findStaticOverlayPackages();
2581
2582            // Find base frameworks (resource packages without code).
2583            scanDirTracedLI(frameworkDir,
2584                    mDefParseFlags
2585                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2586                    scanFlags
2587                    | SCAN_NO_DEX
2588                    | SCAN_AS_SYSTEM
2589                    | SCAN_AS_PRIVILEGED,
2590                    0);
2591
2592            // Collected privileged system packages.
2593            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2594            scanDirTracedLI(privilegedAppDir,
2595                    mDefParseFlags
2596                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2597                    scanFlags
2598                    | SCAN_AS_SYSTEM
2599                    | SCAN_AS_PRIVILEGED,
2600                    0);
2601
2602            // Collect ordinary system packages.
2603            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2604            scanDirTracedLI(systemAppDir,
2605                    mDefParseFlags
2606                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2607                    scanFlags
2608                    | SCAN_AS_SYSTEM,
2609                    0);
2610
2611            // Collected privileged vendor packages.
2612            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2613            try {
2614                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2615            } catch (IOException e) {
2616                // failed to look up canonical path, continue with original one
2617            }
2618            scanDirTracedLI(privilegedVendorAppDir,
2619                    mDefParseFlags
2620                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2621                    scanFlags
2622                    | SCAN_AS_SYSTEM
2623                    | SCAN_AS_VENDOR
2624                    | SCAN_AS_PRIVILEGED,
2625                    0);
2626
2627            // Collect ordinary vendor packages.
2628            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2629            try {
2630                vendorAppDir = vendorAppDir.getCanonicalFile();
2631            } catch (IOException e) {
2632                // failed to look up canonical path, continue with original one
2633            }
2634            scanDirTracedLI(vendorAppDir,
2635                    mDefParseFlags
2636                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2637                    scanFlags
2638                    | SCAN_AS_SYSTEM
2639                    | SCAN_AS_VENDOR,
2640                    0);
2641
2642            // Collect all OEM packages.
2643            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2644            scanDirTracedLI(oemAppDir,
2645                    mDefParseFlags
2646                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2647                    scanFlags
2648                    | SCAN_AS_SYSTEM
2649                    | SCAN_AS_OEM,
2650                    0);
2651
2652            // Collected privileged product packages.
2653            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2654            try {
2655                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2656            } catch (IOException e) {
2657                // failed to look up canonical path, continue with original one
2658            }
2659            scanDirTracedLI(privilegedProductAppDir,
2660                    mDefParseFlags
2661                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2662                    scanFlags
2663                    | SCAN_AS_SYSTEM
2664                    | SCAN_AS_PRODUCT
2665                    | SCAN_AS_PRIVILEGED,
2666                    0);
2667
2668            // Collect ordinary product packages.
2669            File productAppDir = new File(Environment.getProductDirectory(), "app");
2670            try {
2671                productAppDir = productAppDir.getCanonicalFile();
2672            } catch (IOException e) {
2673                // failed to look up canonical path, continue with original one
2674            }
2675            scanDirTracedLI(productAppDir,
2676                    mDefParseFlags
2677                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2678                    scanFlags
2679                    | SCAN_AS_SYSTEM
2680                    | SCAN_AS_PRODUCT,
2681                    0);
2682
2683            // Prune any system packages that no longer exist.
2684            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2685            // Stub packages must either be replaced with full versions in the /data
2686            // partition or be disabled.
2687            final List<String> stubSystemApps = new ArrayList<>();
2688            if (!mOnlyCore) {
2689                // do this first before mucking with mPackages for the "expecting better" case
2690                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2691                while (pkgIterator.hasNext()) {
2692                    final PackageParser.Package pkg = pkgIterator.next();
2693                    if (pkg.isStub) {
2694                        stubSystemApps.add(pkg.packageName);
2695                    }
2696                }
2697
2698                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2699                while (psit.hasNext()) {
2700                    PackageSetting ps = psit.next();
2701
2702                    /*
2703                     * If this is not a system app, it can't be a
2704                     * disable system app.
2705                     */
2706                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2707                        continue;
2708                    }
2709
2710                    /*
2711                     * If the package is scanned, it's not erased.
2712                     */
2713                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2714                    if (scannedPkg != null) {
2715                        /*
2716                         * If the system app is both scanned and in the
2717                         * disabled packages list, then it must have been
2718                         * added via OTA. Remove it from the currently
2719                         * scanned package so the previously user-installed
2720                         * application can be scanned.
2721                         */
2722                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2723                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2724                                    + ps.name + "; removing system app.  Last known codePath="
2725                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2726                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2727                                    + scannedPkg.getLongVersionCode());
2728                            removePackageLI(scannedPkg, true);
2729                            mExpectingBetter.put(ps.name, ps.codePath);
2730                        }
2731
2732                        continue;
2733                    }
2734
2735                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2736                        psit.remove();
2737                        logCriticalInfo(Log.WARN, "System package " + ps.name
2738                                + " no longer exists; it's data will be wiped");
2739                        // Actual deletion of code and data will be handled by later
2740                        // reconciliation step
2741                    } else {
2742                        // we still have a disabled system package, but, it still might have
2743                        // been removed. check the code path still exists and check there's
2744                        // still a package. the latter can happen if an OTA keeps the same
2745                        // code path, but, changes the package name.
2746                        final PackageSetting disabledPs =
2747                                mSettings.getDisabledSystemPkgLPr(ps.name);
2748                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2749                                || disabledPs.pkg == null) {
2750                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2751                        }
2752                    }
2753                }
2754            }
2755
2756            //look for any incomplete package installations
2757            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2758            for (int i = 0; i < deletePkgsList.size(); i++) {
2759                // Actual deletion of code and data will be handled by later
2760                // reconciliation step
2761                final String packageName = deletePkgsList.get(i).name;
2762                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2763                synchronized (mPackages) {
2764                    mSettings.removePackageLPw(packageName);
2765                }
2766            }
2767
2768            //delete tmp files
2769            deleteTempPackageFiles();
2770
2771            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2772
2773            // Remove any shared userIDs that have no associated packages
2774            mSettings.pruneSharedUsersLPw();
2775            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2776            final int systemPackagesCount = mPackages.size();
2777            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2778                    + " ms, packageCount: " + systemPackagesCount
2779                    + " , timePerPackage: "
2780                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2781                    + " , cached: " + cachedSystemApps);
2782            if (mIsUpgrade && systemPackagesCount > 0) {
2783                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2784                        ((int) systemScanTime) / systemPackagesCount);
2785            }
2786            if (!mOnlyCore) {
2787                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2788                        SystemClock.uptimeMillis());
2789                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2790
2791                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2792                        | PackageParser.PARSE_FORWARD_LOCK,
2793                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2794
2795                // Remove disable package settings for updated system apps that were
2796                // removed via an OTA. If the update is no longer present, remove the
2797                // app completely. Otherwise, revoke their system privileges.
2798                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2799                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2800                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2801                    final String msg;
2802                    if (deletedPkg == null) {
2803                        // should have found an update, but, we didn't; remove everything
2804                        msg = "Updated system package " + deletedAppName
2805                                + " no longer exists; removing its data";
2806                        // Actual deletion of code and data will be handled by later
2807                        // reconciliation step
2808                    } else {
2809                        // found an update; revoke system privileges
2810                        msg = "Updated system package + " + deletedAppName
2811                                + " no longer exists; revoking system privileges";
2812
2813                        // Don't do anything if a stub is removed from the system image. If
2814                        // we were to remove the uncompressed version from the /data partition,
2815                        // this is where it'd be done.
2816
2817                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2818                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2819                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2820                    }
2821                    logCriticalInfo(Log.WARN, msg);
2822                }
2823
2824                /*
2825                 * Make sure all system apps that we expected to appear on
2826                 * the userdata partition actually showed up. If they never
2827                 * appeared, crawl back and revive the system version.
2828                 */
2829                for (int i = 0; i < mExpectingBetter.size(); i++) {
2830                    final String packageName = mExpectingBetter.keyAt(i);
2831                    if (!mPackages.containsKey(packageName)) {
2832                        final File scanFile = mExpectingBetter.valueAt(i);
2833
2834                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2835                                + " but never showed up; reverting to system");
2836
2837                        final @ParseFlags int reparseFlags;
2838                        final @ScanFlags int rescanFlags;
2839                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2840                            reparseFlags =
2841                                    mDefParseFlags |
2842                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2843                            rescanFlags =
2844                                    scanFlags
2845                                    | SCAN_AS_SYSTEM
2846                                    | SCAN_AS_PRIVILEGED;
2847                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2848                            reparseFlags =
2849                                    mDefParseFlags |
2850                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2851                            rescanFlags =
2852                                    scanFlags
2853                                    | SCAN_AS_SYSTEM;
2854                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2855                            reparseFlags =
2856                                    mDefParseFlags |
2857                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2858                            rescanFlags =
2859                                    scanFlags
2860                                    | SCAN_AS_SYSTEM
2861                                    | SCAN_AS_VENDOR
2862                                    | SCAN_AS_PRIVILEGED;
2863                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2864                            reparseFlags =
2865                                    mDefParseFlags |
2866                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2867                            rescanFlags =
2868                                    scanFlags
2869                                    | SCAN_AS_SYSTEM
2870                                    | SCAN_AS_VENDOR;
2871                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2872                            reparseFlags =
2873                                    mDefParseFlags |
2874                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2875                            rescanFlags =
2876                                    scanFlags
2877                                    | SCAN_AS_SYSTEM
2878                                    | SCAN_AS_OEM;
2879                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2880                            reparseFlags =
2881                                    mDefParseFlags |
2882                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2883                            rescanFlags =
2884                                    scanFlags
2885                                    | SCAN_AS_SYSTEM
2886                                    | SCAN_AS_PRODUCT
2887                                    | SCAN_AS_PRIVILEGED;
2888                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2889                            reparseFlags =
2890                                    mDefParseFlags |
2891                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2892                            rescanFlags =
2893                                    scanFlags
2894                                    | SCAN_AS_SYSTEM
2895                                    | SCAN_AS_PRODUCT;
2896                        } else {
2897                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2898                            continue;
2899                        }
2900
2901                        mSettings.enableSystemPackageLPw(packageName);
2902
2903                        try {
2904                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2905                        } catch (PackageManagerException e) {
2906                            Slog.e(TAG, "Failed to parse original system package: "
2907                                    + e.getMessage());
2908                        }
2909                    }
2910                }
2911
2912                // Uncompress and install any stubbed system applications.
2913                // This must be done last to ensure all stubs are replaced or disabled.
2914                decompressSystemApplications(stubSystemApps, scanFlags);
2915
2916                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2917                                - cachedSystemApps;
2918
2919                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2920                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2921                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2922                        + " ms, packageCount: " + dataPackagesCount
2923                        + " , timePerPackage: "
2924                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2925                        + " , cached: " + cachedNonSystemApps);
2926                if (mIsUpgrade && dataPackagesCount > 0) {
2927                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2928                            ((int) dataScanTime) / dataPackagesCount);
2929                }
2930            }
2931            mExpectingBetter.clear();
2932
2933            // Resolve the storage manager.
2934            mStorageManagerPackage = getStorageManagerPackageName();
2935
2936            // Resolve protected action filters. Only the setup wizard is allowed to
2937            // have a high priority filter for these actions.
2938            mSetupWizardPackage = getSetupWizardPackageName();
2939            if (mProtectedFilters.size() > 0) {
2940                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2941                    Slog.i(TAG, "No setup wizard;"
2942                        + " All protected intents capped to priority 0");
2943                }
2944                for (ActivityIntentInfo filter : mProtectedFilters) {
2945                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2946                        if (DEBUG_FILTERS) {
2947                            Slog.i(TAG, "Found setup wizard;"
2948                                + " allow priority " + filter.getPriority() + ";"
2949                                + " package: " + filter.activity.info.packageName
2950                                + " activity: " + filter.activity.className
2951                                + " priority: " + filter.getPriority());
2952                        }
2953                        // skip setup wizard; allow it to keep the high priority filter
2954                        continue;
2955                    }
2956                    if (DEBUG_FILTERS) {
2957                        Slog.i(TAG, "Protected action; cap priority to 0;"
2958                                + " package: " + filter.activity.info.packageName
2959                                + " activity: " + filter.activity.className
2960                                + " origPrio: " + filter.getPriority());
2961                    }
2962                    filter.setPriority(0);
2963                }
2964            }
2965            mDeferProtectedFilters = false;
2966            mProtectedFilters.clear();
2967
2968            // Now that we know all of the shared libraries, update all clients to have
2969            // the correct library paths.
2970            updateAllSharedLibrariesLPw(null);
2971
2972            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2973                // NOTE: We ignore potential failures here during a system scan (like
2974                // the rest of the commands above) because there's precious little we
2975                // can do about it. A settings error is reported, though.
2976                final List<String> changedAbiCodePath =
2977                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2978                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2979                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
2980                        final String codePathString = changedAbiCodePath.get(i);
2981                        try {
2982                            mInstaller.rmdex(codePathString,
2983                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2984                        } catch (InstallerException ignored) {
2985                        }
2986                    }
2987                }
2988            }
2989
2990            // Now that we know all the packages we are keeping,
2991            // read and update their last usage times.
2992            mPackageUsage.read(mPackages);
2993            mCompilerStats.read();
2994
2995            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2996                    SystemClock.uptimeMillis());
2997            Slog.i(TAG, "Time to scan packages: "
2998                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2999                    + " seconds");
3000
3001            // If the platform SDK has changed since the last time we booted,
3002            // we need to re-grant app permission to catch any new ones that
3003            // appear.  This is really a hack, and means that apps can in some
3004            // cases get permissions that the user didn't initially explicitly
3005            // allow...  it would be nice to have some better way to handle
3006            // this situation.
3007            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3008            if (sdkUpdated) {
3009                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3010                        + mSdkVersion + "; regranting permissions for internal storage");
3011            }
3012            mPermissionManager.updateAllPermissions(
3013                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3014                    mPermissionCallback);
3015            ver.sdkVersion = mSdkVersion;
3016
3017            // If this is the first boot or an update from pre-M, and it is a normal
3018            // boot, then we need to initialize the default preferred apps across
3019            // all defined users.
3020            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3021                for (UserInfo user : sUserManager.getUsers(true)) {
3022                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3023                    applyFactoryDefaultBrowserLPw(user.id);
3024                    primeDomainVerificationsLPw(user.id);
3025                }
3026            }
3027
3028            // Prepare storage for system user really early during boot,
3029            // since core system apps like SettingsProvider and SystemUI
3030            // can't wait for user to start
3031            final int storageFlags;
3032            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3033                storageFlags = StorageManager.FLAG_STORAGE_DE;
3034            } else {
3035                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3036            }
3037            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3038                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3039                    true /* onlyCoreApps */);
3040            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3041                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3042                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3043                traceLog.traceBegin("AppDataFixup");
3044                try {
3045                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3046                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3047                } catch (InstallerException e) {
3048                    Slog.w(TAG, "Trouble fixing GIDs", e);
3049                }
3050                traceLog.traceEnd();
3051
3052                traceLog.traceBegin("AppDataPrepare");
3053                if (deferPackages == null || deferPackages.isEmpty()) {
3054                    return;
3055                }
3056                int count = 0;
3057                for (String pkgName : deferPackages) {
3058                    PackageParser.Package pkg = null;
3059                    synchronized (mPackages) {
3060                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3061                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3062                            pkg = ps.pkg;
3063                        }
3064                    }
3065                    if (pkg != null) {
3066                        synchronized (mInstallLock) {
3067                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3068                                    true /* maybeMigrateAppData */);
3069                        }
3070                        count++;
3071                    }
3072                }
3073                traceLog.traceEnd();
3074                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3075            }, "prepareAppData");
3076
3077            // If this is first boot after an OTA, and a normal boot, then
3078            // we need to clear code cache directories.
3079            // Note that we do *not* clear the application profiles. These remain valid
3080            // across OTAs and are used to drive profile verification (post OTA) and
3081            // profile compilation (without waiting to collect a fresh set of profiles).
3082            if (mIsUpgrade && !onlyCore) {
3083                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3084                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3085                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3086                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3087                        // No apps are running this early, so no need to freeze
3088                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3089                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3090                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3091                    }
3092                }
3093                ver.fingerprint = Build.FINGERPRINT;
3094            }
3095
3096            checkDefaultBrowser();
3097
3098            // clear only after permissions and other defaults have been updated
3099            mExistingSystemPackages.clear();
3100            mPromoteSystemApps = false;
3101
3102            // All the changes are done during package scanning.
3103            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3104
3105            // can downgrade to reader
3106            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3107            mSettings.writeLPr();
3108            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3109            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3110                    SystemClock.uptimeMillis());
3111
3112            if (!mOnlyCore) {
3113                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3114                mRequiredInstallerPackage = getRequiredInstallerLPr();
3115                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3116                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3117                if (mIntentFilterVerifierComponent != null) {
3118                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3119                            mIntentFilterVerifierComponent);
3120                } else {
3121                    mIntentFilterVerifier = null;
3122                }
3123                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3124                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3125                        SharedLibraryInfo.VERSION_UNDEFINED);
3126                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3127                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3128                        SharedLibraryInfo.VERSION_UNDEFINED);
3129            } else {
3130                mRequiredVerifierPackage = null;
3131                mRequiredInstallerPackage = null;
3132                mRequiredUninstallerPackage = null;
3133                mIntentFilterVerifierComponent = null;
3134                mIntentFilterVerifier = null;
3135                mServicesSystemSharedLibraryPackageName = null;
3136                mSharedSystemSharedLibraryPackageName = null;
3137            }
3138
3139            mInstallerService = new PackageInstallerService(context, this);
3140            final Pair<ComponentName, String> instantAppResolverComponent =
3141                    getInstantAppResolverLPr();
3142            if (instantAppResolverComponent != null) {
3143                if (DEBUG_INSTANT) {
3144                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3145                }
3146                mInstantAppResolverConnection = new InstantAppResolverConnection(
3147                        mContext, instantAppResolverComponent.first,
3148                        instantAppResolverComponent.second);
3149                mInstantAppResolverSettingsComponent =
3150                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3151            } else {
3152                mInstantAppResolverConnection = null;
3153                mInstantAppResolverSettingsComponent = null;
3154            }
3155            updateInstantAppInstallerLocked(null);
3156
3157            // Read and update the usage of dex files.
3158            // Do this at the end of PM init so that all the packages have their
3159            // data directory reconciled.
3160            // At this point we know the code paths of the packages, so we can validate
3161            // the disk file and build the internal cache.
3162            // The usage file is expected to be small so loading and verifying it
3163            // should take a fairly small time compare to the other activities (e.g. package
3164            // scanning).
3165            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3166            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3167            for (int userId : currentUserIds) {
3168                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3169            }
3170            mDexManager.load(userPackages);
3171            if (mIsUpgrade) {
3172                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3173                        (int) (SystemClock.uptimeMillis() - startTime));
3174            }
3175        } // synchronized (mPackages)
3176        } // synchronized (mInstallLock)
3177
3178        // Now after opening every single application zip, make sure they
3179        // are all flushed.  Not really needed, but keeps things nice and
3180        // tidy.
3181        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3182        Runtime.getRuntime().gc();
3183        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3184
3185        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3186        FallbackCategoryProvider.loadFallbacks();
3187        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3188
3189        // The initial scanning above does many calls into installd while
3190        // holding the mPackages lock, but we're mostly interested in yelling
3191        // once we have a booted system.
3192        mInstaller.setWarnIfHeld(mPackages);
3193
3194        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3195    }
3196
3197    /**
3198     * Uncompress and install stub applications.
3199     * <p>In order to save space on the system partition, some applications are shipped in a
3200     * compressed form. In addition the compressed bits for the full application, the
3201     * system image contains a tiny stub comprised of only the Android manifest.
3202     * <p>During the first boot, attempt to uncompress and install the full application. If
3203     * the application can't be installed for any reason, disable the stub and prevent
3204     * uncompressing the full application during future boots.
3205     * <p>In order to forcefully attempt an installation of a full application, go to app
3206     * settings and enable the application.
3207     */
3208    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3209        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3210            final String pkgName = stubSystemApps.get(i);
3211            // skip if the system package is already disabled
3212            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3213                stubSystemApps.remove(i);
3214                continue;
3215            }
3216            // skip if the package isn't installed (?!); this should never happen
3217            final PackageParser.Package pkg = mPackages.get(pkgName);
3218            if (pkg == null) {
3219                stubSystemApps.remove(i);
3220                continue;
3221            }
3222            // skip if the package has been disabled by the user
3223            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3224            if (ps != null) {
3225                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3226                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3227                    stubSystemApps.remove(i);
3228                    continue;
3229                }
3230            }
3231
3232            if (DEBUG_COMPRESSION) {
3233                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3234            }
3235
3236            // uncompress the binary to its eventual destination on /data
3237            final File scanFile = decompressPackage(pkg);
3238            if (scanFile == null) {
3239                continue;
3240            }
3241
3242            // install the package to replace the stub on /system
3243            try {
3244                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3245                removePackageLI(pkg, true /*chatty*/);
3246                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3247                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3248                        UserHandle.USER_SYSTEM, "android");
3249                stubSystemApps.remove(i);
3250                continue;
3251            } catch (PackageManagerException e) {
3252                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3253            }
3254
3255            // any failed attempt to install the package will be cleaned up later
3256        }
3257
3258        // disable any stub still left; these failed to install the full application
3259        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3260            final String pkgName = stubSystemApps.get(i);
3261            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3262            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3263                    UserHandle.USER_SYSTEM, "android");
3264            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3265        }
3266    }
3267
3268    /**
3269     * Decompresses the given package on the system image onto
3270     * the /data partition.
3271     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3272     */
3273    private File decompressPackage(PackageParser.Package pkg) {
3274        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3275        if (compressedFiles == null || compressedFiles.length == 0) {
3276            if (DEBUG_COMPRESSION) {
3277                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3278            }
3279            return null;
3280        }
3281        final File dstCodePath =
3282                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3283        int ret = PackageManager.INSTALL_SUCCEEDED;
3284        try {
3285            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3286            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3287            for (File srcFile : compressedFiles) {
3288                final String srcFileName = srcFile.getName();
3289                final String dstFileName = srcFileName.substring(
3290                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3291                final File dstFile = new File(dstCodePath, dstFileName);
3292                ret = decompressFile(srcFile, dstFile);
3293                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3294                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3295                            + "; pkg: " + pkg.packageName
3296                            + ", file: " + dstFileName);
3297                    break;
3298                }
3299            }
3300        } catch (ErrnoException e) {
3301            logCriticalInfo(Log.ERROR, "Failed to decompress"
3302                    + "; pkg: " + pkg.packageName
3303                    + ", err: " + e.errno);
3304        }
3305        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3306            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3307            NativeLibraryHelper.Handle handle = null;
3308            try {
3309                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3310                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3311                        null /*abiOverride*/);
3312            } catch (IOException e) {
3313                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3314                        + "; pkg: " + pkg.packageName);
3315                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3316            } finally {
3317                IoUtils.closeQuietly(handle);
3318            }
3319        }
3320        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3321            if (dstCodePath == null || !dstCodePath.exists()) {
3322                return null;
3323            }
3324            removeCodePathLI(dstCodePath);
3325            return null;
3326        }
3327
3328        return dstCodePath;
3329    }
3330
3331    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3332        // we're only interested in updating the installer appliction when 1) it's not
3333        // already set or 2) the modified package is the installer
3334        if (mInstantAppInstallerActivity != null
3335                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3336                        .equals(modifiedPackage)) {
3337            return;
3338        }
3339        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3340    }
3341
3342    private static File preparePackageParserCache(boolean isUpgrade) {
3343        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3344            return null;
3345        }
3346
3347        // Disable package parsing on eng builds to allow for faster incremental development.
3348        if (Build.IS_ENG) {
3349            return null;
3350        }
3351
3352        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3353            Slog.i(TAG, "Disabling package parser cache due to system property.");
3354            return null;
3355        }
3356
3357        // The base directory for the package parser cache lives under /data/system/.
3358        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3359                "package_cache");
3360        if (cacheBaseDir == null) {
3361            return null;
3362        }
3363
3364        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3365        // This also serves to "GC" unused entries when the package cache version changes (which
3366        // can only happen during upgrades).
3367        if (isUpgrade) {
3368            FileUtils.deleteContents(cacheBaseDir);
3369        }
3370
3371
3372        // Return the versioned package cache directory. This is something like
3373        // "/data/system/package_cache/1"
3374        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3375
3376        // The following is a workaround to aid development on non-numbered userdebug
3377        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3378        // the system partition is newer.
3379        //
3380        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3381        // that starts with "eng." to signify that this is an engineering build and not
3382        // destined for release.
3383        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3384            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3385
3386            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3387            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3388            // in general and should not be used for production changes. In this specific case,
3389            // we know that they will work.
3390            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3391            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3392                FileUtils.deleteContents(cacheBaseDir);
3393                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3394            }
3395        }
3396
3397        return cacheDir;
3398    }
3399
3400    @Override
3401    public boolean isFirstBoot() {
3402        // allow instant applications
3403        return mFirstBoot;
3404    }
3405
3406    @Override
3407    public boolean isOnlyCoreApps() {
3408        // allow instant applications
3409        return mOnlyCore;
3410    }
3411
3412    @Override
3413    public boolean isUpgrade() {
3414        // allow instant applications
3415        // The system property allows testing ota flow when upgraded to the same image.
3416        return mIsUpgrade || SystemProperties.getBoolean(
3417                "persist.pm.mock-upgrade", false /* default */);
3418    }
3419
3420    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3421        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3422
3423        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3424                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3425                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3426        if (matches.size() == 1) {
3427            return matches.get(0).getComponentInfo().packageName;
3428        } else if (matches.size() == 0) {
3429            Log.e(TAG, "There should probably be a verifier, but, none were found");
3430            return null;
3431        }
3432        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3433    }
3434
3435    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3436        synchronized (mPackages) {
3437            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3438            if (libraryEntry == null) {
3439                throw new IllegalStateException("Missing required shared library:" + name);
3440            }
3441            return libraryEntry.apk;
3442        }
3443    }
3444
3445    private @NonNull String getRequiredInstallerLPr() {
3446        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3447        intent.addCategory(Intent.CATEGORY_DEFAULT);
3448        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3449
3450        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3451                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3452                UserHandle.USER_SYSTEM);
3453        if (matches.size() == 1) {
3454            ResolveInfo resolveInfo = matches.get(0);
3455            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3456                throw new RuntimeException("The installer must be a privileged app");
3457            }
3458            return matches.get(0).getComponentInfo().packageName;
3459        } else {
3460            throw new RuntimeException("There must be exactly one installer; found " + matches);
3461        }
3462    }
3463
3464    private @NonNull String getRequiredUninstallerLPr() {
3465        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3466        intent.addCategory(Intent.CATEGORY_DEFAULT);
3467        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3468
3469        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3470                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3471                UserHandle.USER_SYSTEM);
3472        if (resolveInfo == null ||
3473                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3474            throw new RuntimeException("There must be exactly one uninstaller; found "
3475                    + resolveInfo);
3476        }
3477        return resolveInfo.getComponentInfo().packageName;
3478    }
3479
3480    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3481        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3482
3483        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3484                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3485                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3486        ResolveInfo best = null;
3487        final int N = matches.size();
3488        for (int i = 0; i < N; i++) {
3489            final ResolveInfo cur = matches.get(i);
3490            final String packageName = cur.getComponentInfo().packageName;
3491            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3492                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3493                continue;
3494            }
3495
3496            if (best == null || cur.priority > best.priority) {
3497                best = cur;
3498            }
3499        }
3500
3501        if (best != null) {
3502            return best.getComponentInfo().getComponentName();
3503        }
3504        Slog.w(TAG, "Intent filter verifier not found");
3505        return null;
3506    }
3507
3508    @Override
3509    public @Nullable ComponentName getInstantAppResolverComponent() {
3510        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3511            return null;
3512        }
3513        synchronized (mPackages) {
3514            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3515            if (instantAppResolver == null) {
3516                return null;
3517            }
3518            return instantAppResolver.first;
3519        }
3520    }
3521
3522    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3523        final String[] packageArray =
3524                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3525        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3526            if (DEBUG_INSTANT) {
3527                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3528            }
3529            return null;
3530        }
3531
3532        final int callingUid = Binder.getCallingUid();
3533        final int resolveFlags =
3534                MATCH_DIRECT_BOOT_AWARE
3535                | MATCH_DIRECT_BOOT_UNAWARE
3536                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3537        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3538        final Intent resolverIntent = new Intent(actionName);
3539        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3540                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3541        final int N = resolvers.size();
3542        if (N == 0) {
3543            if (DEBUG_INSTANT) {
3544                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3545            }
3546            return null;
3547        }
3548
3549        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3550        for (int i = 0; i < N; i++) {
3551            final ResolveInfo info = resolvers.get(i);
3552
3553            if (info.serviceInfo == null) {
3554                continue;
3555            }
3556
3557            final String packageName = info.serviceInfo.packageName;
3558            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3559                if (DEBUG_INSTANT) {
3560                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3561                            + " pkg: " + packageName + ", info:" + info);
3562                }
3563                continue;
3564            }
3565
3566            if (DEBUG_INSTANT) {
3567                Slog.v(TAG, "Ephemeral resolver found;"
3568                        + " pkg: " + packageName + ", info:" + info);
3569            }
3570            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3571        }
3572        if (DEBUG_INSTANT) {
3573            Slog.v(TAG, "Ephemeral resolver NOT found");
3574        }
3575        return null;
3576    }
3577
3578    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3579        String[] orderedActions = Build.IS_ENG
3580                ? new String[]{
3581                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3582                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3583                : new String[]{
3584                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3585
3586        final int resolveFlags =
3587                MATCH_DIRECT_BOOT_AWARE
3588                        | MATCH_DIRECT_BOOT_UNAWARE
3589                        | Intent.FLAG_IGNORE_EPHEMERAL
3590                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3591        final Intent intent = new Intent();
3592        intent.addCategory(Intent.CATEGORY_DEFAULT);
3593        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3594        List<ResolveInfo> matches = null;
3595        for (String action : orderedActions) {
3596            intent.setAction(action);
3597            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3598                    resolveFlags, UserHandle.USER_SYSTEM);
3599            if (matches.isEmpty()) {
3600                if (DEBUG_INSTANT) {
3601                    Slog.d(TAG, "Instant App installer not found with " + action);
3602                }
3603            } else {
3604                break;
3605            }
3606        }
3607        Iterator<ResolveInfo> iter = matches.iterator();
3608        while (iter.hasNext()) {
3609            final ResolveInfo rInfo = iter.next();
3610            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3611            if (ps != null) {
3612                final PermissionsState permissionsState = ps.getPermissionsState();
3613                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3614                        || Build.IS_ENG) {
3615                    continue;
3616                }
3617            }
3618            iter.remove();
3619        }
3620        if (matches.size() == 0) {
3621            return null;
3622        } else if (matches.size() == 1) {
3623            return (ActivityInfo) matches.get(0).getComponentInfo();
3624        } else {
3625            throw new RuntimeException(
3626                    "There must be at most one ephemeral installer; found " + matches);
3627        }
3628    }
3629
3630    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3631            @NonNull ComponentName resolver) {
3632        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3633                .addCategory(Intent.CATEGORY_DEFAULT)
3634                .setPackage(resolver.getPackageName());
3635        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3636        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3637                UserHandle.USER_SYSTEM);
3638        if (matches.isEmpty()) {
3639            return null;
3640        }
3641        return matches.get(0).getComponentInfo().getComponentName();
3642    }
3643
3644    private void primeDomainVerificationsLPw(int userId) {
3645        if (DEBUG_DOMAIN_VERIFICATION) {
3646            Slog.d(TAG, "Priming domain verifications in user " + userId);
3647        }
3648
3649        SystemConfig systemConfig = SystemConfig.getInstance();
3650        ArraySet<String> packages = systemConfig.getLinkedApps();
3651
3652        for (String packageName : packages) {
3653            PackageParser.Package pkg = mPackages.get(packageName);
3654            if (pkg != null) {
3655                if (!pkg.isSystem()) {
3656                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3657                    continue;
3658                }
3659
3660                ArraySet<String> domains = null;
3661                for (PackageParser.Activity a : pkg.activities) {
3662                    for (ActivityIntentInfo filter : a.intents) {
3663                        if (hasValidDomains(filter)) {
3664                            if (domains == null) {
3665                                domains = new ArraySet<String>();
3666                            }
3667                            domains.addAll(filter.getHostsList());
3668                        }
3669                    }
3670                }
3671
3672                if (domains != null && domains.size() > 0) {
3673                    if (DEBUG_DOMAIN_VERIFICATION) {
3674                        Slog.v(TAG, "      + " + packageName);
3675                    }
3676                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3677                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3678                    // and then 'always' in the per-user state actually used for intent resolution.
3679                    final IntentFilterVerificationInfo ivi;
3680                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3681                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3682                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3683                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3684                } else {
3685                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3686                            + "' does not handle web links");
3687                }
3688            } else {
3689                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3690            }
3691        }
3692
3693        scheduleWritePackageRestrictionsLocked(userId);
3694        scheduleWriteSettingsLocked();
3695    }
3696
3697    private void applyFactoryDefaultBrowserLPw(int userId) {
3698        // The default browser app's package name is stored in a string resource,
3699        // with a product-specific overlay used for vendor customization.
3700        String browserPkg = mContext.getResources().getString(
3701                com.android.internal.R.string.default_browser);
3702        if (!TextUtils.isEmpty(browserPkg)) {
3703            // non-empty string => required to be a known package
3704            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3705            if (ps == null) {
3706                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3707                browserPkg = null;
3708            } else {
3709                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3710            }
3711        }
3712
3713        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3714        // default.  If there's more than one, just leave everything alone.
3715        if (browserPkg == null) {
3716            calculateDefaultBrowserLPw(userId);
3717        }
3718    }
3719
3720    private void calculateDefaultBrowserLPw(int userId) {
3721        List<String> allBrowsers = resolveAllBrowserApps(userId);
3722        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3723        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3724    }
3725
3726    private List<String> resolveAllBrowserApps(int userId) {
3727        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3728        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3729                PackageManager.MATCH_ALL, userId);
3730
3731        final int count = list.size();
3732        List<String> result = new ArrayList<String>(count);
3733        for (int i=0; i<count; i++) {
3734            ResolveInfo info = list.get(i);
3735            if (info.activityInfo == null
3736                    || !info.handleAllWebDataURI
3737                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3738                    || result.contains(info.activityInfo.packageName)) {
3739                continue;
3740            }
3741            result.add(info.activityInfo.packageName);
3742        }
3743
3744        return result;
3745    }
3746
3747    private boolean packageIsBrowser(String packageName, int userId) {
3748        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3749                PackageManager.MATCH_ALL, userId);
3750        final int N = list.size();
3751        for (int i = 0; i < N; i++) {
3752            ResolveInfo info = list.get(i);
3753            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3754                return true;
3755            }
3756        }
3757        return false;
3758    }
3759
3760    private void checkDefaultBrowser() {
3761        final int myUserId = UserHandle.myUserId();
3762        final String packageName = getDefaultBrowserPackageName(myUserId);
3763        if (packageName != null) {
3764            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3765            if (info == null) {
3766                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3767                synchronized (mPackages) {
3768                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3769                }
3770            }
3771        }
3772    }
3773
3774    @Override
3775    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3776            throws RemoteException {
3777        try {
3778            return super.onTransact(code, data, reply, flags);
3779        } catch (RuntimeException e) {
3780            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3781                Slog.wtf(TAG, "Package Manager Crash", e);
3782            }
3783            throw e;
3784        }
3785    }
3786
3787    static int[] appendInts(int[] cur, int[] add) {
3788        if (add == null) return cur;
3789        if (cur == null) return add;
3790        final int N = add.length;
3791        for (int i=0; i<N; i++) {
3792            cur = appendInt(cur, add[i]);
3793        }
3794        return cur;
3795    }
3796
3797    /**
3798     * Returns whether or not a full application can see an instant application.
3799     * <p>
3800     * Currently, there are three cases in which this can occur:
3801     * <ol>
3802     * <li>The calling application is a "special" process. Special processes
3803     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3804     * <li>The calling application has the permission
3805     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3806     * <li>The calling application is the default launcher on the
3807     *     system partition.</li>
3808     * </ol>
3809     */
3810    private boolean canViewInstantApps(int callingUid, int userId) {
3811        if (callingUid < Process.FIRST_APPLICATION_UID) {
3812            return true;
3813        }
3814        if (mContext.checkCallingOrSelfPermission(
3815                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3816            return true;
3817        }
3818        if (mContext.checkCallingOrSelfPermission(
3819                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3820            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3821            if (homeComponent != null
3822                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3823                return true;
3824            }
3825        }
3826        return false;
3827    }
3828
3829    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3830        if (!sUserManager.exists(userId)) return null;
3831        if (ps == null) {
3832            return null;
3833        }
3834        final int callingUid = Binder.getCallingUid();
3835        // Filter out ephemeral app metadata:
3836        //   * The system/shell/root can see metadata for any app
3837        //   * An installed app can see metadata for 1) other installed apps
3838        //     and 2) ephemeral apps that have explicitly interacted with it
3839        //   * Ephemeral apps can only see their own data and exposed installed apps
3840        //   * Holding a signature permission allows seeing instant apps
3841        if (filterAppAccessLPr(ps, callingUid, userId)) {
3842            return null;
3843        }
3844
3845        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3846                && ps.isSystem()) {
3847            flags |= MATCH_ANY_USER;
3848        }
3849
3850        final PackageUserState state = ps.readUserState(userId);
3851        PackageParser.Package p = ps.pkg;
3852        if (p != null) {
3853            final PermissionsState permissionsState = ps.getPermissionsState();
3854
3855            // Compute GIDs only if requested
3856            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3857                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3858            // Compute granted permissions only if package has requested permissions
3859            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3860                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3861
3862            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3863                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3864
3865            if (packageInfo == null) {
3866                return null;
3867            }
3868
3869            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3870                    resolveExternalPackageNameLPr(p);
3871
3872            return packageInfo;
3873        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3874            PackageInfo pi = new PackageInfo();
3875            pi.packageName = ps.name;
3876            pi.setLongVersionCode(ps.versionCode);
3877            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3878            pi.firstInstallTime = ps.firstInstallTime;
3879            pi.lastUpdateTime = ps.lastUpdateTime;
3880
3881            ApplicationInfo ai = new ApplicationInfo();
3882            ai.packageName = ps.name;
3883            ai.uid = UserHandle.getUid(userId, ps.appId);
3884            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3885            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3886            ai.versionCode = ps.versionCode;
3887            ai.flags = ps.pkgFlags;
3888            ai.privateFlags = ps.pkgPrivateFlags;
3889            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3890
3891            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3892                    + ps.name + "]. Provides a minimum info.");
3893            return pi;
3894        } else {
3895            return null;
3896        }
3897    }
3898
3899    @Override
3900    public void checkPackageStartable(String packageName, int userId) {
3901        final int callingUid = Binder.getCallingUid();
3902        if (getInstantAppPackageName(callingUid) != null) {
3903            throw new SecurityException("Instant applications don't have access to this method");
3904        }
3905        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3906        synchronized (mPackages) {
3907            final PackageSetting ps = mSettings.mPackages.get(packageName);
3908            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3909                throw new SecurityException("Package " + packageName + " was not found!");
3910            }
3911
3912            if (!ps.getInstalled(userId)) {
3913                throw new SecurityException(
3914                        "Package " + packageName + " was not installed for user " + userId + "!");
3915            }
3916
3917            if (mSafeMode && !ps.isSystem()) {
3918                throw new SecurityException("Package " + packageName + " not a system app!");
3919            }
3920
3921            if (mFrozenPackages.contains(packageName)) {
3922                throw new SecurityException("Package " + packageName + " is currently frozen!");
3923            }
3924
3925            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3926                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3927            }
3928        }
3929    }
3930
3931    @Override
3932    public boolean isPackageAvailable(String packageName, int userId) {
3933        if (!sUserManager.exists(userId)) return false;
3934        final int callingUid = Binder.getCallingUid();
3935        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3936                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3937        synchronized (mPackages) {
3938            PackageParser.Package p = mPackages.get(packageName);
3939            if (p != null) {
3940                final PackageSetting ps = (PackageSetting) p.mExtras;
3941                if (filterAppAccessLPr(ps, callingUid, userId)) {
3942                    return false;
3943                }
3944                if (ps != null) {
3945                    final PackageUserState state = ps.readUserState(userId);
3946                    if (state != null) {
3947                        return PackageParser.isAvailable(state);
3948                    }
3949                }
3950            }
3951        }
3952        return false;
3953    }
3954
3955    @Override
3956    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3957        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3958                flags, Binder.getCallingUid(), userId);
3959    }
3960
3961    @Override
3962    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3963            int flags, int userId) {
3964        return getPackageInfoInternal(versionedPackage.getPackageName(),
3965                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3966    }
3967
3968    /**
3969     * Important: The provided filterCallingUid is used exclusively to filter out packages
3970     * that can be seen based on user state. It's typically the original caller uid prior
3971     * to clearing. Because it can only be provided by trusted code, it's value can be
3972     * trusted and will be used as-is; unlike userId which will be validated by this method.
3973     */
3974    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3975            int flags, int filterCallingUid, int userId) {
3976        if (!sUserManager.exists(userId)) return null;
3977        flags = updateFlagsForPackage(flags, userId, packageName);
3978        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3979                false /* requireFullPermission */, false /* checkShell */, "get package info");
3980
3981        // reader
3982        synchronized (mPackages) {
3983            // Normalize package name to handle renamed packages and static libs
3984            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3985
3986            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3987            if (matchFactoryOnly) {
3988                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3989                if (ps != null) {
3990                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3991                        return null;
3992                    }
3993                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3994                        return null;
3995                    }
3996                    return generatePackageInfo(ps, flags, userId);
3997                }
3998            }
3999
4000            PackageParser.Package p = mPackages.get(packageName);
4001            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4002                return null;
4003            }
4004            if (DEBUG_PACKAGE_INFO)
4005                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4006            if (p != null) {
4007                final PackageSetting ps = (PackageSetting) p.mExtras;
4008                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4009                    return null;
4010                }
4011                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4012                    return null;
4013                }
4014                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4015            }
4016            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4017                final PackageSetting ps = mSettings.mPackages.get(packageName);
4018                if (ps == null) return null;
4019                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4020                    return null;
4021                }
4022                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4023                    return null;
4024                }
4025                return generatePackageInfo(ps, flags, userId);
4026            }
4027        }
4028        return null;
4029    }
4030
4031    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4032        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4033            return true;
4034        }
4035        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4036            return true;
4037        }
4038        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4039            return true;
4040        }
4041        return false;
4042    }
4043
4044    private boolean isComponentVisibleToInstantApp(
4045            @Nullable ComponentName component, @ComponentType int type) {
4046        if (type == TYPE_ACTIVITY) {
4047            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4048            return activity != null
4049                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4050                    : false;
4051        } else if (type == TYPE_RECEIVER) {
4052            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4053            return activity != null
4054                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4055                    : false;
4056        } else if (type == TYPE_SERVICE) {
4057            final PackageParser.Service service = mServices.mServices.get(component);
4058            return service != null
4059                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4060                    : false;
4061        } else if (type == TYPE_PROVIDER) {
4062            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4063            return provider != null
4064                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4065                    : false;
4066        } else if (type == TYPE_UNKNOWN) {
4067            return isComponentVisibleToInstantApp(component);
4068        }
4069        return false;
4070    }
4071
4072    /**
4073     * Returns whether or not access to the application should be filtered.
4074     * <p>
4075     * Access may be limited based upon whether the calling or target applications
4076     * are instant applications.
4077     *
4078     * @see #canAccessInstantApps(int)
4079     */
4080    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4081            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4082        // if we're in an isolated process, get the real calling UID
4083        if (Process.isIsolated(callingUid)) {
4084            callingUid = mIsolatedOwners.get(callingUid);
4085        }
4086        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4087        final boolean callerIsInstantApp = instantAppPkgName != null;
4088        if (ps == null) {
4089            if (callerIsInstantApp) {
4090                // pretend the application exists, but, needs to be filtered
4091                return true;
4092            }
4093            return false;
4094        }
4095        // if the target and caller are the same application, don't filter
4096        if (isCallerSameApp(ps.name, callingUid)) {
4097            return false;
4098        }
4099        if (callerIsInstantApp) {
4100            // request for a specific component; if it hasn't been explicitly exposed, filter
4101            if (component != null) {
4102                return !isComponentVisibleToInstantApp(component, componentType);
4103            }
4104            // request for application; if no components have been explicitly exposed, filter
4105            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4106        }
4107        if (ps.getInstantApp(userId)) {
4108            // caller can see all components of all instant applications, don't filter
4109            if (canViewInstantApps(callingUid, userId)) {
4110                return false;
4111            }
4112            // request for a specific instant application component, filter
4113            if (component != null) {
4114                return true;
4115            }
4116            // request for an instant application; if the caller hasn't been granted access, filter
4117            return !mInstantAppRegistry.isInstantAccessGranted(
4118                    userId, UserHandle.getAppId(callingUid), ps.appId);
4119        }
4120        return false;
4121    }
4122
4123    /**
4124     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4125     */
4126    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4127        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4128    }
4129
4130    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4131            int flags) {
4132        // Callers can access only the libs they depend on, otherwise they need to explicitly
4133        // ask for the shared libraries given the caller is allowed to access all static libs.
4134        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4135            // System/shell/root get to see all static libs
4136            final int appId = UserHandle.getAppId(uid);
4137            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4138                    || appId == Process.ROOT_UID) {
4139                return false;
4140            }
4141        }
4142
4143        // No package means no static lib as it is always on internal storage
4144        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4145            return false;
4146        }
4147
4148        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4149                ps.pkg.staticSharedLibVersion);
4150        if (libEntry == null) {
4151            return false;
4152        }
4153
4154        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4155        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4156        if (uidPackageNames == null) {
4157            return true;
4158        }
4159
4160        for (String uidPackageName : uidPackageNames) {
4161            if (ps.name.equals(uidPackageName)) {
4162                return false;
4163            }
4164            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4165            if (uidPs != null) {
4166                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4167                        libEntry.info.getName());
4168                if (index < 0) {
4169                    continue;
4170                }
4171                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4172                    return false;
4173                }
4174            }
4175        }
4176        return true;
4177    }
4178
4179    @Override
4180    public String[] currentToCanonicalPackageNames(String[] names) {
4181        final int callingUid = Binder.getCallingUid();
4182        if (getInstantAppPackageName(callingUid) != null) {
4183            return names;
4184        }
4185        final String[] out = new String[names.length];
4186        // reader
4187        synchronized (mPackages) {
4188            final int callingUserId = UserHandle.getUserId(callingUid);
4189            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4190            for (int i=names.length-1; i>=0; i--) {
4191                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4192                boolean translateName = false;
4193                if (ps != null && ps.realName != null) {
4194                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4195                    translateName = !targetIsInstantApp
4196                            || canViewInstantApps
4197                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4198                                    UserHandle.getAppId(callingUid), ps.appId);
4199                }
4200                out[i] = translateName ? ps.realName : names[i];
4201            }
4202        }
4203        return out;
4204    }
4205
4206    @Override
4207    public String[] canonicalToCurrentPackageNames(String[] names) {
4208        final int callingUid = Binder.getCallingUid();
4209        if (getInstantAppPackageName(callingUid) != null) {
4210            return names;
4211        }
4212        final String[] out = new String[names.length];
4213        // reader
4214        synchronized (mPackages) {
4215            final int callingUserId = UserHandle.getUserId(callingUid);
4216            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4217            for (int i=names.length-1; i>=0; i--) {
4218                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4219                boolean translateName = false;
4220                if (cur != null) {
4221                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4222                    final boolean targetIsInstantApp =
4223                            ps != null && ps.getInstantApp(callingUserId);
4224                    translateName = !targetIsInstantApp
4225                            || canViewInstantApps
4226                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4227                                    UserHandle.getAppId(callingUid), ps.appId);
4228                }
4229                out[i] = translateName ? cur : names[i];
4230            }
4231        }
4232        return out;
4233    }
4234
4235    @Override
4236    public int getPackageUid(String packageName, int flags, int userId) {
4237        if (!sUserManager.exists(userId)) return -1;
4238        final int callingUid = Binder.getCallingUid();
4239        flags = updateFlagsForPackage(flags, userId, packageName);
4240        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4241                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4242
4243        // reader
4244        synchronized (mPackages) {
4245            final PackageParser.Package p = mPackages.get(packageName);
4246            if (p != null && p.isMatch(flags)) {
4247                PackageSetting ps = (PackageSetting) p.mExtras;
4248                if (filterAppAccessLPr(ps, callingUid, userId)) {
4249                    return -1;
4250                }
4251                return UserHandle.getUid(userId, p.applicationInfo.uid);
4252            }
4253            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4254                final PackageSetting ps = mSettings.mPackages.get(packageName);
4255                if (ps != null && ps.isMatch(flags)
4256                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4257                    return UserHandle.getUid(userId, ps.appId);
4258                }
4259            }
4260        }
4261
4262        return -1;
4263    }
4264
4265    @Override
4266    public int[] getPackageGids(String packageName, int flags, int userId) {
4267        if (!sUserManager.exists(userId)) return null;
4268        final int callingUid = Binder.getCallingUid();
4269        flags = updateFlagsForPackage(flags, userId, packageName);
4270        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4271                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4272
4273        // reader
4274        synchronized (mPackages) {
4275            final PackageParser.Package p = mPackages.get(packageName);
4276            if (p != null && p.isMatch(flags)) {
4277                PackageSetting ps = (PackageSetting) p.mExtras;
4278                if (filterAppAccessLPr(ps, callingUid, userId)) {
4279                    return null;
4280                }
4281                // TODO: Shouldn't this be checking for package installed state for userId and
4282                // return null?
4283                return ps.getPermissionsState().computeGids(userId);
4284            }
4285            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4286                final PackageSetting ps = mSettings.mPackages.get(packageName);
4287                if (ps != null && ps.isMatch(flags)
4288                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4289                    return ps.getPermissionsState().computeGids(userId);
4290                }
4291            }
4292        }
4293
4294        return null;
4295    }
4296
4297    @Override
4298    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4299        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4300    }
4301
4302    @Override
4303    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4304            int flags) {
4305        final List<PermissionInfo> permissionList =
4306                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4307        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4308    }
4309
4310    @Override
4311    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4312        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4313    }
4314
4315    @Override
4316    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4317        final List<PermissionGroupInfo> permissionList =
4318                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4319        return (permissionList == null)
4320                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4321    }
4322
4323    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4324            int filterCallingUid, int userId) {
4325        if (!sUserManager.exists(userId)) return null;
4326        PackageSetting ps = mSettings.mPackages.get(packageName);
4327        if (ps != null) {
4328            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4329                return null;
4330            }
4331            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4332                return null;
4333            }
4334            if (ps.pkg == null) {
4335                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4336                if (pInfo != null) {
4337                    return pInfo.applicationInfo;
4338                }
4339                return null;
4340            }
4341            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4342                    ps.readUserState(userId), userId);
4343            if (ai != null) {
4344                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4345            }
4346            return ai;
4347        }
4348        return null;
4349    }
4350
4351    @Override
4352    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4353        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4354    }
4355
4356    /**
4357     * Important: The provided filterCallingUid is used exclusively to filter out applications
4358     * that can be seen based on user state. It's typically the original caller uid prior
4359     * to clearing. Because it can only be provided by trusted code, it's value can be
4360     * trusted and will be used as-is; unlike userId which will be validated by this method.
4361     */
4362    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4363            int filterCallingUid, int userId) {
4364        if (!sUserManager.exists(userId)) return null;
4365        flags = updateFlagsForApplication(flags, userId, packageName);
4366        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4367                false /* requireFullPermission */, false /* checkShell */, "get application info");
4368
4369        // writer
4370        synchronized (mPackages) {
4371            // Normalize package name to handle renamed packages and static libs
4372            packageName = resolveInternalPackageNameLPr(packageName,
4373                    PackageManager.VERSION_CODE_HIGHEST);
4374
4375            PackageParser.Package p = mPackages.get(packageName);
4376            if (DEBUG_PACKAGE_INFO) Log.v(
4377                    TAG, "getApplicationInfo " + packageName
4378                    + ": " + p);
4379            if (p != null) {
4380                PackageSetting ps = mSettings.mPackages.get(packageName);
4381                if (ps == null) return null;
4382                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4383                    return null;
4384                }
4385                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4386                    return null;
4387                }
4388                // Note: isEnabledLP() does not apply here - always return info
4389                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4390                        p, flags, ps.readUserState(userId), userId);
4391                if (ai != null) {
4392                    ai.packageName = resolveExternalPackageNameLPr(p);
4393                }
4394                return ai;
4395            }
4396            if ("android".equals(packageName)||"system".equals(packageName)) {
4397                return mAndroidApplication;
4398            }
4399            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4400                // Already generates the external package name
4401                return generateApplicationInfoFromSettingsLPw(packageName,
4402                        flags, filterCallingUid, userId);
4403            }
4404        }
4405        return null;
4406    }
4407
4408    private String normalizePackageNameLPr(String packageName) {
4409        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4410        return normalizedPackageName != null ? normalizedPackageName : packageName;
4411    }
4412
4413    @Override
4414    public void deletePreloadsFileCache() {
4415        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4416            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4417        }
4418        File dir = Environment.getDataPreloadsFileCacheDirectory();
4419        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4420        FileUtils.deleteContents(dir);
4421    }
4422
4423    @Override
4424    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4425            final int storageFlags, final IPackageDataObserver observer) {
4426        mContext.enforceCallingOrSelfPermission(
4427                android.Manifest.permission.CLEAR_APP_CACHE, null);
4428        mHandler.post(() -> {
4429            boolean success = false;
4430            try {
4431                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4432                success = true;
4433            } catch (IOException e) {
4434                Slog.w(TAG, e);
4435            }
4436            if (observer != null) {
4437                try {
4438                    observer.onRemoveCompleted(null, success);
4439                } catch (RemoteException e) {
4440                    Slog.w(TAG, e);
4441                }
4442            }
4443        });
4444    }
4445
4446    @Override
4447    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4448            final int storageFlags, final IntentSender pi) {
4449        mContext.enforceCallingOrSelfPermission(
4450                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4451        mHandler.post(() -> {
4452            boolean success = false;
4453            try {
4454                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4455                success = true;
4456            } catch (IOException e) {
4457                Slog.w(TAG, e);
4458            }
4459            if (pi != null) {
4460                try {
4461                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4462                } catch (SendIntentException e) {
4463                    Slog.w(TAG, e);
4464                }
4465            }
4466        });
4467    }
4468
4469    /**
4470     * Blocking call to clear various types of cached data across the system
4471     * until the requested bytes are available.
4472     */
4473    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4474        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4475        final File file = storage.findPathForUuid(volumeUuid);
4476        if (file.getUsableSpace() >= bytes) return;
4477
4478        if (ENABLE_FREE_CACHE_V2) {
4479            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4480                    volumeUuid);
4481            final boolean aggressive = (storageFlags
4482                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4483            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4484
4485            // 1. Pre-flight to determine if we have any chance to succeed
4486            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4487            if (internalVolume && (aggressive || SystemProperties
4488                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4489                deletePreloadsFileCache();
4490                if (file.getUsableSpace() >= bytes) return;
4491            }
4492
4493            // 3. Consider parsed APK data (aggressive only)
4494            if (internalVolume && aggressive) {
4495                FileUtils.deleteContents(mCacheDir);
4496                if (file.getUsableSpace() >= bytes) return;
4497            }
4498
4499            // 4. Consider cached app data (above quotas)
4500            try {
4501                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4502                        Installer.FLAG_FREE_CACHE_V2);
4503            } catch (InstallerException ignored) {
4504            }
4505            if (file.getUsableSpace() >= bytes) return;
4506
4507            // 5. Consider shared libraries with refcount=0 and age>min cache period
4508            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4509                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4510                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4511                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4512                return;
4513            }
4514
4515            // 6. Consider dexopt output (aggressive only)
4516            // TODO: Implement
4517
4518            // 7. Consider installed instant apps unused longer than min cache period
4519            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4520                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4521                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4522                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4523                return;
4524            }
4525
4526            // 8. Consider cached app data (below quotas)
4527            try {
4528                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4529                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4530            } catch (InstallerException ignored) {
4531            }
4532            if (file.getUsableSpace() >= bytes) return;
4533
4534            // 9. Consider DropBox entries
4535            // TODO: Implement
4536
4537            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4538            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4539                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4540                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4541                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4542                return;
4543            }
4544        } else {
4545            try {
4546                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4547            } catch (InstallerException ignored) {
4548            }
4549            if (file.getUsableSpace() >= bytes) return;
4550        }
4551
4552        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4553    }
4554
4555    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4556            throws IOException {
4557        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4558        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4559
4560        List<VersionedPackage> packagesToDelete = null;
4561        final long now = System.currentTimeMillis();
4562
4563        synchronized (mPackages) {
4564            final int[] allUsers = sUserManager.getUserIds();
4565            final int libCount = mSharedLibraries.size();
4566            for (int i = 0; i < libCount; i++) {
4567                final LongSparseArray<SharedLibraryEntry> versionedLib
4568                        = mSharedLibraries.valueAt(i);
4569                if (versionedLib == null) {
4570                    continue;
4571                }
4572                final int versionCount = versionedLib.size();
4573                for (int j = 0; j < versionCount; j++) {
4574                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4575                    // Skip packages that are not static shared libs.
4576                    if (!libInfo.isStatic()) {
4577                        break;
4578                    }
4579                    // Important: We skip static shared libs used for some user since
4580                    // in such a case we need to keep the APK on the device. The check for
4581                    // a lib being used for any user is performed by the uninstall call.
4582                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4583                    // Resolve the package name - we use synthetic package names internally
4584                    final String internalPackageName = resolveInternalPackageNameLPr(
4585                            declaringPackage.getPackageName(),
4586                            declaringPackage.getLongVersionCode());
4587                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4588                    // Skip unused static shared libs cached less than the min period
4589                    // to prevent pruning a lib needed by a subsequently installed package.
4590                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4591                        continue;
4592                    }
4593                    if (packagesToDelete == null) {
4594                        packagesToDelete = new ArrayList<>();
4595                    }
4596                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4597                            declaringPackage.getLongVersionCode()));
4598                }
4599            }
4600        }
4601
4602        if (packagesToDelete != null) {
4603            final int packageCount = packagesToDelete.size();
4604            for (int i = 0; i < packageCount; i++) {
4605                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4606                // Delete the package synchronously (will fail of the lib used for any user).
4607                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4608                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4609                                == PackageManager.DELETE_SUCCEEDED) {
4610                    if (volume.getUsableSpace() >= neededSpace) {
4611                        return true;
4612                    }
4613                }
4614            }
4615        }
4616
4617        return false;
4618    }
4619
4620    /**
4621     * Update given flags based on encryption status of current user.
4622     */
4623    private int updateFlags(int flags, int userId) {
4624        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4625                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4626            // Caller expressed an explicit opinion about what encryption
4627            // aware/unaware components they want to see, so fall through and
4628            // give them what they want
4629        } else {
4630            // Caller expressed no opinion, so match based on user state
4631            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4632                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4633            } else {
4634                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4635            }
4636        }
4637        return flags;
4638    }
4639
4640    private UserManagerInternal getUserManagerInternal() {
4641        if (mUserManagerInternal == null) {
4642            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4643        }
4644        return mUserManagerInternal;
4645    }
4646
4647    private ActivityManagerInternal getActivityManagerInternal() {
4648        if (mActivityManagerInternal == null) {
4649            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4650        }
4651        return mActivityManagerInternal;
4652    }
4653
4654
4655    private DeviceIdleController.LocalService getDeviceIdleController() {
4656        if (mDeviceIdleController == null) {
4657            mDeviceIdleController =
4658                    LocalServices.getService(DeviceIdleController.LocalService.class);
4659        }
4660        return mDeviceIdleController;
4661    }
4662
4663    /**
4664     * Update given flags when being used to request {@link PackageInfo}.
4665     */
4666    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4667        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4668        boolean triaged = true;
4669        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4670                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4671            // Caller is asking for component details, so they'd better be
4672            // asking for specific encryption matching behavior, or be triaged
4673            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4674                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4675                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4676                triaged = false;
4677            }
4678        }
4679        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4680                | PackageManager.MATCH_SYSTEM_ONLY
4681                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4682            triaged = false;
4683        }
4684        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4685            mPermissionManager.enforceCrossUserPermission(
4686                    Binder.getCallingUid(), userId, false, false,
4687                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4688                    + Debug.getCallers(5));
4689        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4690                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4691            // If the caller wants all packages and has a restricted profile associated with it,
4692            // then match all users. This is to make sure that launchers that need to access work
4693            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4694            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4695            flags |= PackageManager.MATCH_ANY_USER;
4696        }
4697        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4698            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4699                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4700        }
4701        return updateFlags(flags, userId);
4702    }
4703
4704    /**
4705     * Update given flags when being used to request {@link ApplicationInfo}.
4706     */
4707    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4708        return updateFlagsForPackage(flags, userId, cookie);
4709    }
4710
4711    /**
4712     * Update given flags when being used to request {@link ComponentInfo}.
4713     */
4714    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4715        if (cookie instanceof Intent) {
4716            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4717                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4718            }
4719        }
4720
4721        boolean triaged = true;
4722        // Caller is asking for component details, so they'd better be
4723        // asking for specific encryption matching behavior, or be triaged
4724        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4725                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4726                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4727            triaged = false;
4728        }
4729        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4730            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4731                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4732        }
4733
4734        return updateFlags(flags, userId);
4735    }
4736
4737    /**
4738     * Update given intent when being used to request {@link ResolveInfo}.
4739     */
4740    private Intent updateIntentForResolve(Intent intent) {
4741        if (intent.getSelector() != null) {
4742            intent = intent.getSelector();
4743        }
4744        if (DEBUG_PREFERRED) {
4745            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4746        }
4747        return intent;
4748    }
4749
4750    /**
4751     * Update given flags when being used to request {@link ResolveInfo}.
4752     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4753     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4754     * flag set. However, this flag is only honoured in three circumstances:
4755     * <ul>
4756     * <li>when called from a system process</li>
4757     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4758     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4759     * action and a {@code android.intent.category.BROWSABLE} category</li>
4760     * </ul>
4761     */
4762    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4763        return updateFlagsForResolve(flags, userId, intent, callingUid,
4764                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4765    }
4766    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4767            boolean wantInstantApps) {
4768        return updateFlagsForResolve(flags, userId, intent, callingUid,
4769                wantInstantApps, false /*onlyExposedExplicitly*/);
4770    }
4771    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4772            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4773        // Safe mode means we shouldn't match any third-party components
4774        if (mSafeMode) {
4775            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4776        }
4777        if (getInstantAppPackageName(callingUid) != null) {
4778            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4779            if (onlyExposedExplicitly) {
4780                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4781            }
4782            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4783            flags |= PackageManager.MATCH_INSTANT;
4784        } else {
4785            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4786            final boolean allowMatchInstant = wantInstantApps
4787                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4788            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4789                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4790            if (!allowMatchInstant) {
4791                flags &= ~PackageManager.MATCH_INSTANT;
4792            }
4793        }
4794        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4795    }
4796
4797    @Override
4798    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4799        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4800    }
4801
4802    /**
4803     * Important: The provided filterCallingUid is used exclusively to filter out activities
4804     * that can be seen based on user state. It's typically the original caller uid prior
4805     * to clearing. Because it can only be provided by trusted code, it's value can be
4806     * trusted and will be used as-is; unlike userId which will be validated by this method.
4807     */
4808    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4809            int filterCallingUid, int userId) {
4810        if (!sUserManager.exists(userId)) return null;
4811        flags = updateFlagsForComponent(flags, userId, component);
4812
4813        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4814            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4815                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4816        }
4817
4818        synchronized (mPackages) {
4819            PackageParser.Activity a = mActivities.mActivities.get(component);
4820
4821            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4822            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4823                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4824                if (ps == null) return null;
4825                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4826                    return null;
4827                }
4828                return PackageParser.generateActivityInfo(
4829                        a, flags, ps.readUserState(userId), userId);
4830            }
4831            if (mResolveComponentName.equals(component)) {
4832                return PackageParser.generateActivityInfo(
4833                        mResolveActivity, flags, new PackageUserState(), userId);
4834            }
4835        }
4836        return null;
4837    }
4838
4839    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4840        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4841            return false;
4842        }
4843        final long token = Binder.clearCallingIdentity();
4844        try {
4845            final int callingUserId = UserHandle.getUserId(callingUid);
4846            if (ActivityManager.getCurrentUser() != callingUserId) {
4847                return false;
4848            }
4849            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4850        } finally {
4851            Binder.restoreCallingIdentity(token);
4852        }
4853    }
4854
4855    @Override
4856    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4857            String resolvedType) {
4858        synchronized (mPackages) {
4859            if (component.equals(mResolveComponentName)) {
4860                // The resolver supports EVERYTHING!
4861                return true;
4862            }
4863            final int callingUid = Binder.getCallingUid();
4864            final int callingUserId = UserHandle.getUserId(callingUid);
4865            PackageParser.Activity a = mActivities.mActivities.get(component);
4866            if (a == null) {
4867                return false;
4868            }
4869            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4870            if (ps == null) {
4871                return false;
4872            }
4873            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4874                return false;
4875            }
4876            for (int i=0; i<a.intents.size(); i++) {
4877                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4878                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4879                    return true;
4880                }
4881            }
4882            return false;
4883        }
4884    }
4885
4886    @Override
4887    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4888        if (!sUserManager.exists(userId)) return null;
4889        final int callingUid = Binder.getCallingUid();
4890        flags = updateFlagsForComponent(flags, userId, component);
4891        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4892                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4893        synchronized (mPackages) {
4894            PackageParser.Activity a = mReceivers.mActivities.get(component);
4895            if (DEBUG_PACKAGE_INFO) Log.v(
4896                TAG, "getReceiverInfo " + component + ": " + a);
4897            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4898                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4899                if (ps == null) return null;
4900                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4901                    return null;
4902                }
4903                return PackageParser.generateActivityInfo(
4904                        a, flags, ps.readUserState(userId), userId);
4905            }
4906        }
4907        return null;
4908    }
4909
4910    @Override
4911    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4912            int flags, int userId) {
4913        if (!sUserManager.exists(userId)) return null;
4914        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4915        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4916            return null;
4917        }
4918
4919        flags = updateFlagsForPackage(flags, userId, null);
4920
4921        final boolean canSeeStaticLibraries =
4922                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4923                        == PERMISSION_GRANTED
4924                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4925                        == PERMISSION_GRANTED
4926                || canRequestPackageInstallsInternal(packageName,
4927                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4928                        false  /* throwIfPermNotDeclared*/)
4929                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4930                        == PERMISSION_GRANTED;
4931
4932        synchronized (mPackages) {
4933            List<SharedLibraryInfo> result = null;
4934
4935            final int libCount = mSharedLibraries.size();
4936            for (int i = 0; i < libCount; i++) {
4937                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4938                if (versionedLib == null) {
4939                    continue;
4940                }
4941
4942                final int versionCount = versionedLib.size();
4943                for (int j = 0; j < versionCount; j++) {
4944                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4945                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4946                        break;
4947                    }
4948                    final long identity = Binder.clearCallingIdentity();
4949                    try {
4950                        PackageInfo packageInfo = getPackageInfoVersioned(
4951                                libInfo.getDeclaringPackage(), flags
4952                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4953                        if (packageInfo == null) {
4954                            continue;
4955                        }
4956                    } finally {
4957                        Binder.restoreCallingIdentity(identity);
4958                    }
4959
4960                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4961                            libInfo.getLongVersion(), libInfo.getType(),
4962                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4963                            flags, userId));
4964
4965                    if (result == null) {
4966                        result = new ArrayList<>();
4967                    }
4968                    result.add(resLibInfo);
4969                }
4970            }
4971
4972            return result != null ? new ParceledListSlice<>(result) : null;
4973        }
4974    }
4975
4976    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4977            SharedLibraryInfo libInfo, int flags, int userId) {
4978        List<VersionedPackage> versionedPackages = null;
4979        final int packageCount = mSettings.mPackages.size();
4980        for (int i = 0; i < packageCount; i++) {
4981            PackageSetting ps = mSettings.mPackages.valueAt(i);
4982
4983            if (ps == null) {
4984                continue;
4985            }
4986
4987            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4988                continue;
4989            }
4990
4991            final String libName = libInfo.getName();
4992            if (libInfo.isStatic()) {
4993                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4994                if (libIdx < 0) {
4995                    continue;
4996                }
4997                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
4998                    continue;
4999                }
5000                if (versionedPackages == null) {
5001                    versionedPackages = new ArrayList<>();
5002                }
5003                // If the dependent is a static shared lib, use the public package name
5004                String dependentPackageName = ps.name;
5005                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5006                    dependentPackageName = ps.pkg.manifestPackageName;
5007                }
5008                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5009            } else if (ps.pkg != null) {
5010                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5011                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5012                    if (versionedPackages == null) {
5013                        versionedPackages = new ArrayList<>();
5014                    }
5015                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5016                }
5017            }
5018        }
5019
5020        return versionedPackages;
5021    }
5022
5023    @Override
5024    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5025        if (!sUserManager.exists(userId)) return null;
5026        final int callingUid = Binder.getCallingUid();
5027        flags = updateFlagsForComponent(flags, userId, component);
5028        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5029                false /* requireFullPermission */, false /* checkShell */, "get service info");
5030        synchronized (mPackages) {
5031            PackageParser.Service s = mServices.mServices.get(component);
5032            if (DEBUG_PACKAGE_INFO) Log.v(
5033                TAG, "getServiceInfo " + component + ": " + s);
5034            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5035                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5036                if (ps == null) return null;
5037                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5038                    return null;
5039                }
5040                return PackageParser.generateServiceInfo(
5041                        s, flags, ps.readUserState(userId), userId);
5042            }
5043        }
5044        return null;
5045    }
5046
5047    @Override
5048    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5049        if (!sUserManager.exists(userId)) return null;
5050        final int callingUid = Binder.getCallingUid();
5051        flags = updateFlagsForComponent(flags, userId, component);
5052        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5053                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5054        synchronized (mPackages) {
5055            PackageParser.Provider p = mProviders.mProviders.get(component);
5056            if (DEBUG_PACKAGE_INFO) Log.v(
5057                TAG, "getProviderInfo " + component + ": " + p);
5058            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5059                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5060                if (ps == null) return null;
5061                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5062                    return null;
5063                }
5064                return PackageParser.generateProviderInfo(
5065                        p, flags, ps.readUserState(userId), userId);
5066            }
5067        }
5068        return null;
5069    }
5070
5071    @Override
5072    public String[] getSystemSharedLibraryNames() {
5073        // allow instant applications
5074        synchronized (mPackages) {
5075            Set<String> libs = null;
5076            final int libCount = mSharedLibraries.size();
5077            for (int i = 0; i < libCount; i++) {
5078                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5079                if (versionedLib == null) {
5080                    continue;
5081                }
5082                final int versionCount = versionedLib.size();
5083                for (int j = 0; j < versionCount; j++) {
5084                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5085                    if (!libEntry.info.isStatic()) {
5086                        if (libs == null) {
5087                            libs = new ArraySet<>();
5088                        }
5089                        libs.add(libEntry.info.getName());
5090                        break;
5091                    }
5092                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5093                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5094                            UserHandle.getUserId(Binder.getCallingUid()),
5095                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5096                        if (libs == null) {
5097                            libs = new ArraySet<>();
5098                        }
5099                        libs.add(libEntry.info.getName());
5100                        break;
5101                    }
5102                }
5103            }
5104
5105            if (libs != null) {
5106                String[] libsArray = new String[libs.size()];
5107                libs.toArray(libsArray);
5108                return libsArray;
5109            }
5110
5111            return null;
5112        }
5113    }
5114
5115    @Override
5116    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5117        // allow instant applications
5118        synchronized (mPackages) {
5119            return mServicesSystemSharedLibraryPackageName;
5120        }
5121    }
5122
5123    @Override
5124    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5125        // allow instant applications
5126        synchronized (mPackages) {
5127            return mSharedSystemSharedLibraryPackageName;
5128        }
5129    }
5130
5131    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5132        for (int i = userList.length - 1; i >= 0; --i) {
5133            final int userId = userList[i];
5134            // don't add instant app to the list of updates
5135            if (pkgSetting.getInstantApp(userId)) {
5136                continue;
5137            }
5138            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5139            if (changedPackages == null) {
5140                changedPackages = new SparseArray<>();
5141                mChangedPackages.put(userId, changedPackages);
5142            }
5143            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5144            if (sequenceNumbers == null) {
5145                sequenceNumbers = new HashMap<>();
5146                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5147            }
5148            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5149            if (sequenceNumber != null) {
5150                changedPackages.remove(sequenceNumber);
5151            }
5152            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5153            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5154        }
5155        mChangedPackagesSequenceNumber++;
5156    }
5157
5158    @Override
5159    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5160        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5161            return null;
5162        }
5163        synchronized (mPackages) {
5164            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5165                return null;
5166            }
5167            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5168            if (changedPackages == null) {
5169                return null;
5170            }
5171            final List<String> packageNames =
5172                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5173            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5174                final String packageName = changedPackages.get(i);
5175                if (packageName != null) {
5176                    packageNames.add(packageName);
5177                }
5178            }
5179            return packageNames.isEmpty()
5180                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5181        }
5182    }
5183
5184    @Override
5185    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5186        // allow instant applications
5187        ArrayList<FeatureInfo> res;
5188        synchronized (mAvailableFeatures) {
5189            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5190            res.addAll(mAvailableFeatures.values());
5191        }
5192        final FeatureInfo fi = new FeatureInfo();
5193        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5194                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5195        res.add(fi);
5196
5197        return new ParceledListSlice<>(res);
5198    }
5199
5200    @Override
5201    public boolean hasSystemFeature(String name, int version) {
5202        // allow instant applications
5203        synchronized (mAvailableFeatures) {
5204            final FeatureInfo feat = mAvailableFeatures.get(name);
5205            if (feat == null) {
5206                return false;
5207            } else {
5208                return feat.version >= version;
5209            }
5210        }
5211    }
5212
5213    @Override
5214    public int checkPermission(String permName, String pkgName, int userId) {
5215        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5216    }
5217
5218    @Override
5219    public int checkUidPermission(String permName, int uid) {
5220        synchronized (mPackages) {
5221            final String[] packageNames = getPackagesForUid(uid);
5222            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5223                    ? mPackages.get(packageNames[0])
5224                    : null;
5225            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5226        }
5227    }
5228
5229    @Override
5230    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5231        if (UserHandle.getCallingUserId() != userId) {
5232            mContext.enforceCallingPermission(
5233                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5234                    "isPermissionRevokedByPolicy for user " + userId);
5235        }
5236
5237        if (checkPermission(permission, packageName, userId)
5238                == PackageManager.PERMISSION_GRANTED) {
5239            return false;
5240        }
5241
5242        final int callingUid = Binder.getCallingUid();
5243        if (getInstantAppPackageName(callingUid) != null) {
5244            if (!isCallerSameApp(packageName, callingUid)) {
5245                return false;
5246            }
5247        } else {
5248            if (isInstantApp(packageName, userId)) {
5249                return false;
5250            }
5251        }
5252
5253        final long identity = Binder.clearCallingIdentity();
5254        try {
5255            final int flags = getPermissionFlags(permission, packageName, userId);
5256            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5257        } finally {
5258            Binder.restoreCallingIdentity(identity);
5259        }
5260    }
5261
5262    @Override
5263    public String getPermissionControllerPackageName() {
5264        synchronized (mPackages) {
5265            return mRequiredInstallerPackage;
5266        }
5267    }
5268
5269    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5270        return mPermissionManager.addDynamicPermission(
5271                info, async, getCallingUid(), new PermissionCallback() {
5272                    @Override
5273                    public void onPermissionChanged() {
5274                        if (!async) {
5275                            mSettings.writeLPr();
5276                        } else {
5277                            scheduleWriteSettingsLocked();
5278                        }
5279                    }
5280                });
5281    }
5282
5283    @Override
5284    public boolean addPermission(PermissionInfo info) {
5285        synchronized (mPackages) {
5286            return addDynamicPermission(info, false);
5287        }
5288    }
5289
5290    @Override
5291    public boolean addPermissionAsync(PermissionInfo info) {
5292        synchronized (mPackages) {
5293            return addDynamicPermission(info, true);
5294        }
5295    }
5296
5297    @Override
5298    public void removePermission(String permName) {
5299        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5300    }
5301
5302    @Override
5303    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5304        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5305                getCallingUid(), userId, mPermissionCallback);
5306    }
5307
5308    @Override
5309    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5310        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5311                getCallingUid(), userId, mPermissionCallback);
5312    }
5313
5314    @Override
5315    public void resetRuntimePermissions() {
5316        mContext.enforceCallingOrSelfPermission(
5317                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5318                "revokeRuntimePermission");
5319
5320        int callingUid = Binder.getCallingUid();
5321        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5322            mContext.enforceCallingOrSelfPermission(
5323                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5324                    "resetRuntimePermissions");
5325        }
5326
5327        synchronized (mPackages) {
5328            mPermissionManager.updateAllPermissions(
5329                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5330                    mPermissionCallback);
5331            for (int userId : UserManagerService.getInstance().getUserIds()) {
5332                final int packageCount = mPackages.size();
5333                for (int i = 0; i < packageCount; i++) {
5334                    PackageParser.Package pkg = mPackages.valueAt(i);
5335                    if (!(pkg.mExtras instanceof PackageSetting)) {
5336                        continue;
5337                    }
5338                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5339                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5340                }
5341            }
5342        }
5343    }
5344
5345    @Override
5346    public int getPermissionFlags(String permName, String packageName, int userId) {
5347        return mPermissionManager.getPermissionFlags(
5348                permName, packageName, getCallingUid(), userId);
5349    }
5350
5351    @Override
5352    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5353            int flagValues, int userId) {
5354        mPermissionManager.updatePermissionFlags(
5355                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5356                mPermissionCallback);
5357    }
5358
5359    /**
5360     * Update the permission flags for all packages and runtime permissions of a user in order
5361     * to allow device or profile owner to remove POLICY_FIXED.
5362     */
5363    @Override
5364    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5365        synchronized (mPackages) {
5366            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5367                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5368                    mPermissionCallback);
5369            if (changed) {
5370                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5371            }
5372        }
5373    }
5374
5375    @Override
5376    public boolean shouldShowRequestPermissionRationale(String permissionName,
5377            String packageName, int userId) {
5378        if (UserHandle.getCallingUserId() != userId) {
5379            mContext.enforceCallingPermission(
5380                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5381                    "canShowRequestPermissionRationale for user " + userId);
5382        }
5383
5384        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5385        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5386            return false;
5387        }
5388
5389        if (checkPermission(permissionName, packageName, userId)
5390                == PackageManager.PERMISSION_GRANTED) {
5391            return false;
5392        }
5393
5394        final int flags;
5395
5396        final long identity = Binder.clearCallingIdentity();
5397        try {
5398            flags = getPermissionFlags(permissionName,
5399                    packageName, userId);
5400        } finally {
5401            Binder.restoreCallingIdentity(identity);
5402        }
5403
5404        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5405                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5406                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5407
5408        if ((flags & fixedFlags) != 0) {
5409            return false;
5410        }
5411
5412        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5413    }
5414
5415    @Override
5416    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5417        mContext.enforceCallingOrSelfPermission(
5418                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5419                "addOnPermissionsChangeListener");
5420
5421        synchronized (mPackages) {
5422            mOnPermissionChangeListeners.addListenerLocked(listener);
5423        }
5424    }
5425
5426    @Override
5427    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5428        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5429            throw new SecurityException("Instant applications don't have access to this method");
5430        }
5431        synchronized (mPackages) {
5432            mOnPermissionChangeListeners.removeListenerLocked(listener);
5433        }
5434    }
5435
5436    @Override
5437    public boolean isProtectedBroadcast(String actionName) {
5438        // allow instant applications
5439        synchronized (mProtectedBroadcasts) {
5440            if (mProtectedBroadcasts.contains(actionName)) {
5441                return true;
5442            } else if (actionName != null) {
5443                // TODO: remove these terrible hacks
5444                if (actionName.startsWith("android.net.netmon.lingerExpired")
5445                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5446                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5447                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5448                    return true;
5449                }
5450            }
5451        }
5452        return false;
5453    }
5454
5455    @Override
5456    public int checkSignatures(String pkg1, String pkg2) {
5457        synchronized (mPackages) {
5458            final PackageParser.Package p1 = mPackages.get(pkg1);
5459            final PackageParser.Package p2 = mPackages.get(pkg2);
5460            if (p1 == null || p1.mExtras == null
5461                    || p2 == null || p2.mExtras == null) {
5462                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5463            }
5464            final int callingUid = Binder.getCallingUid();
5465            final int callingUserId = UserHandle.getUserId(callingUid);
5466            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5467            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5468            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5469                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5470                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5471            }
5472            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5473        }
5474    }
5475
5476    @Override
5477    public int checkUidSignatures(int uid1, int uid2) {
5478        final int callingUid = Binder.getCallingUid();
5479        final int callingUserId = UserHandle.getUserId(callingUid);
5480        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5481        // Map to base uids.
5482        uid1 = UserHandle.getAppId(uid1);
5483        uid2 = UserHandle.getAppId(uid2);
5484        // reader
5485        synchronized (mPackages) {
5486            Signature[] s1;
5487            Signature[] s2;
5488            Object obj = mSettings.getUserIdLPr(uid1);
5489            if (obj != null) {
5490                if (obj instanceof SharedUserSetting) {
5491                    if (isCallerInstantApp) {
5492                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5493                    }
5494                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5495                } else if (obj instanceof PackageSetting) {
5496                    final PackageSetting ps = (PackageSetting) obj;
5497                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5498                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5499                    }
5500                    s1 = ps.signatures.mSigningDetails.signatures;
5501                } else {
5502                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5503                }
5504            } else {
5505                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5506            }
5507            obj = mSettings.getUserIdLPr(uid2);
5508            if (obj != null) {
5509                if (obj instanceof SharedUserSetting) {
5510                    if (isCallerInstantApp) {
5511                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5512                    }
5513                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5514                } else if (obj instanceof PackageSetting) {
5515                    final PackageSetting ps = (PackageSetting) obj;
5516                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5517                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5518                    }
5519                    s2 = ps.signatures.mSigningDetails.signatures;
5520                } else {
5521                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5522                }
5523            } else {
5524                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5525            }
5526            return compareSignatures(s1, s2);
5527        }
5528    }
5529
5530    @Override
5531    public boolean hasSigningCertificate(
5532            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5533
5534        synchronized (mPackages) {
5535            final PackageParser.Package p = mPackages.get(packageName);
5536            if (p == null || p.mExtras == null) {
5537                return false;
5538            }
5539            final int callingUid = Binder.getCallingUid();
5540            final int callingUserId = UserHandle.getUserId(callingUid);
5541            final PackageSetting ps = (PackageSetting) p.mExtras;
5542            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5543                return false;
5544            }
5545            switch (type) {
5546                case CERT_INPUT_RAW_X509:
5547                    return p.mSigningDetails.hasCertificate(certificate);
5548                case CERT_INPUT_SHA256:
5549                    return p.mSigningDetails.hasSha256Certificate(certificate);
5550                default:
5551                    return false;
5552            }
5553        }
5554    }
5555
5556    @Override
5557    public boolean hasUidSigningCertificate(
5558            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5559        final int callingUid = Binder.getCallingUid();
5560        final int callingUserId = UserHandle.getUserId(callingUid);
5561        // Map to base uids.
5562        uid = UserHandle.getAppId(uid);
5563        // reader
5564        synchronized (mPackages) {
5565            final PackageParser.SigningDetails signingDetails;
5566            final Object obj = mSettings.getUserIdLPr(uid);
5567            if (obj != null) {
5568                if (obj instanceof SharedUserSetting) {
5569                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5570                    if (isCallerInstantApp) {
5571                        return false;
5572                    }
5573                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5574                } else if (obj instanceof PackageSetting) {
5575                    final PackageSetting ps = (PackageSetting) obj;
5576                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5577                        return false;
5578                    }
5579                    signingDetails = ps.signatures.mSigningDetails;
5580                } else {
5581                    return false;
5582                }
5583            } else {
5584                return false;
5585            }
5586            switch (type) {
5587                case CERT_INPUT_RAW_X509:
5588                    return signingDetails.hasCertificate(certificate);
5589                case CERT_INPUT_SHA256:
5590                    return signingDetails.hasSha256Certificate(certificate);
5591                default:
5592                    return false;
5593            }
5594        }
5595    }
5596
5597    /**
5598     * This method should typically only be used when granting or revoking
5599     * permissions, since the app may immediately restart after this call.
5600     * <p>
5601     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5602     * guard your work against the app being relaunched.
5603     */
5604    private void killUid(int appId, int userId, String reason) {
5605        final long identity = Binder.clearCallingIdentity();
5606        try {
5607            IActivityManager am = ActivityManager.getService();
5608            if (am != null) {
5609                try {
5610                    am.killUid(appId, userId, reason);
5611                } catch (RemoteException e) {
5612                    /* ignore - same process */
5613                }
5614            }
5615        } finally {
5616            Binder.restoreCallingIdentity(identity);
5617        }
5618    }
5619
5620    /**
5621     * If the database version for this type of package (internal storage or
5622     * external storage) is less than the version where package signatures
5623     * were updated, return true.
5624     */
5625    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5626        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5627        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5628    }
5629
5630    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5631        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5632        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5633    }
5634
5635    @Override
5636    public List<String> getAllPackages() {
5637        final int callingUid = Binder.getCallingUid();
5638        final int callingUserId = UserHandle.getUserId(callingUid);
5639        synchronized (mPackages) {
5640            if (canViewInstantApps(callingUid, callingUserId)) {
5641                return new ArrayList<String>(mPackages.keySet());
5642            }
5643            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5644            final List<String> result = new ArrayList<>();
5645            if (instantAppPkgName != null) {
5646                // caller is an instant application; filter unexposed applications
5647                for (PackageParser.Package pkg : mPackages.values()) {
5648                    if (!pkg.visibleToInstantApps) {
5649                        continue;
5650                    }
5651                    result.add(pkg.packageName);
5652                }
5653            } else {
5654                // caller is a normal application; filter instant applications
5655                for (PackageParser.Package pkg : mPackages.values()) {
5656                    final PackageSetting ps =
5657                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5658                    if (ps != null
5659                            && ps.getInstantApp(callingUserId)
5660                            && !mInstantAppRegistry.isInstantAccessGranted(
5661                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5662                        continue;
5663                    }
5664                    result.add(pkg.packageName);
5665                }
5666            }
5667            return result;
5668        }
5669    }
5670
5671    @Override
5672    public String[] getPackagesForUid(int uid) {
5673        final int callingUid = Binder.getCallingUid();
5674        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5675        final int userId = UserHandle.getUserId(uid);
5676        uid = UserHandle.getAppId(uid);
5677        // reader
5678        synchronized (mPackages) {
5679            Object obj = mSettings.getUserIdLPr(uid);
5680            if (obj instanceof SharedUserSetting) {
5681                if (isCallerInstantApp) {
5682                    return null;
5683                }
5684                final SharedUserSetting sus = (SharedUserSetting) obj;
5685                final int N = sus.packages.size();
5686                String[] res = new String[N];
5687                final Iterator<PackageSetting> it = sus.packages.iterator();
5688                int i = 0;
5689                while (it.hasNext()) {
5690                    PackageSetting ps = it.next();
5691                    if (ps.getInstalled(userId)) {
5692                        res[i++] = ps.name;
5693                    } else {
5694                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5695                    }
5696                }
5697                return res;
5698            } else if (obj instanceof PackageSetting) {
5699                final PackageSetting ps = (PackageSetting) obj;
5700                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5701                    return new String[]{ps.name};
5702                }
5703            }
5704        }
5705        return null;
5706    }
5707
5708    @Override
5709    public String getNameForUid(int uid) {
5710        final int callingUid = Binder.getCallingUid();
5711        if (getInstantAppPackageName(callingUid) != null) {
5712            return null;
5713        }
5714        synchronized (mPackages) {
5715            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5716            if (obj instanceof SharedUserSetting) {
5717                final SharedUserSetting sus = (SharedUserSetting) obj;
5718                return sus.name + ":" + sus.userId;
5719            } else if (obj instanceof PackageSetting) {
5720                final PackageSetting ps = (PackageSetting) obj;
5721                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5722                    return null;
5723                }
5724                return ps.name;
5725            }
5726            return null;
5727        }
5728    }
5729
5730    @Override
5731    public String[] getNamesForUids(int[] uids) {
5732        if (uids == null || uids.length == 0) {
5733            return null;
5734        }
5735        final int callingUid = Binder.getCallingUid();
5736        if (getInstantAppPackageName(callingUid) != null) {
5737            return null;
5738        }
5739        final String[] names = new String[uids.length];
5740        synchronized (mPackages) {
5741            for (int i = uids.length - 1; i >= 0; i--) {
5742                final int uid = uids[i];
5743                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5744                if (obj instanceof SharedUserSetting) {
5745                    final SharedUserSetting sus = (SharedUserSetting) obj;
5746                    names[i] = "shared:" + sus.name;
5747                } else if (obj instanceof PackageSetting) {
5748                    final PackageSetting ps = (PackageSetting) obj;
5749                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5750                        names[i] = null;
5751                    } else {
5752                        names[i] = ps.name;
5753                    }
5754                } else {
5755                    names[i] = null;
5756                }
5757            }
5758        }
5759        return names;
5760    }
5761
5762    @Override
5763    public int getUidForSharedUser(String sharedUserName) {
5764        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5765            return -1;
5766        }
5767        if (sharedUserName == null) {
5768            return -1;
5769        }
5770        // reader
5771        synchronized (mPackages) {
5772            SharedUserSetting suid;
5773            try {
5774                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5775                if (suid != null) {
5776                    return suid.userId;
5777                }
5778            } catch (PackageManagerException ignore) {
5779                // can't happen, but, still need to catch it
5780            }
5781            return -1;
5782        }
5783    }
5784
5785    @Override
5786    public int getFlagsForUid(int uid) {
5787        final int callingUid = Binder.getCallingUid();
5788        if (getInstantAppPackageName(callingUid) != null) {
5789            return 0;
5790        }
5791        synchronized (mPackages) {
5792            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5793            if (obj instanceof SharedUserSetting) {
5794                final SharedUserSetting sus = (SharedUserSetting) obj;
5795                return sus.pkgFlags;
5796            } else if (obj instanceof PackageSetting) {
5797                final PackageSetting ps = (PackageSetting) obj;
5798                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5799                    return 0;
5800                }
5801                return ps.pkgFlags;
5802            }
5803        }
5804        return 0;
5805    }
5806
5807    @Override
5808    public int getPrivateFlagsForUid(int uid) {
5809        final int callingUid = Binder.getCallingUid();
5810        if (getInstantAppPackageName(callingUid) != null) {
5811            return 0;
5812        }
5813        synchronized (mPackages) {
5814            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5815            if (obj instanceof SharedUserSetting) {
5816                final SharedUserSetting sus = (SharedUserSetting) obj;
5817                return sus.pkgPrivateFlags;
5818            } else if (obj instanceof PackageSetting) {
5819                final PackageSetting ps = (PackageSetting) obj;
5820                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5821                    return 0;
5822                }
5823                return ps.pkgPrivateFlags;
5824            }
5825        }
5826        return 0;
5827    }
5828
5829    @Override
5830    public boolean isUidPrivileged(int uid) {
5831        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5832            return false;
5833        }
5834        uid = UserHandle.getAppId(uid);
5835        // reader
5836        synchronized (mPackages) {
5837            Object obj = mSettings.getUserIdLPr(uid);
5838            if (obj instanceof SharedUserSetting) {
5839                final SharedUserSetting sus = (SharedUserSetting) obj;
5840                final Iterator<PackageSetting> it = sus.packages.iterator();
5841                while (it.hasNext()) {
5842                    if (it.next().isPrivileged()) {
5843                        return true;
5844                    }
5845                }
5846            } else if (obj instanceof PackageSetting) {
5847                final PackageSetting ps = (PackageSetting) obj;
5848                return ps.isPrivileged();
5849            }
5850        }
5851        return false;
5852    }
5853
5854    @Override
5855    public String[] getAppOpPermissionPackages(String permName) {
5856        return mPermissionManager.getAppOpPermissionPackages(permName);
5857    }
5858
5859    @Override
5860    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5861            int flags, int userId) {
5862        return resolveIntentInternal(
5863                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5864    }
5865
5866    /**
5867     * Normally instant apps can only be resolved when they're visible to the caller.
5868     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5869     * since we need to allow the system to start any installed application.
5870     */
5871    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5872            int flags, int userId, boolean resolveForStart) {
5873        try {
5874            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5875
5876            if (!sUserManager.exists(userId)) return null;
5877            final int callingUid = Binder.getCallingUid();
5878            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5879            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5880                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5881
5882            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5883            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5884                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5885            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5886
5887            final ResolveInfo bestChoice =
5888                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5889            return bestChoice;
5890        } finally {
5891            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5892        }
5893    }
5894
5895    @Override
5896    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5897        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5898            throw new SecurityException(
5899                    "findPersistentPreferredActivity can only be run by the system");
5900        }
5901        if (!sUserManager.exists(userId)) {
5902            return null;
5903        }
5904        final int callingUid = Binder.getCallingUid();
5905        intent = updateIntentForResolve(intent);
5906        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5907        final int flags = updateFlagsForResolve(
5908                0, userId, intent, callingUid, false /*includeInstantApps*/);
5909        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5910                userId);
5911        synchronized (mPackages) {
5912            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5913                    userId);
5914        }
5915    }
5916
5917    @Override
5918    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5919            IntentFilter filter, int match, ComponentName activity) {
5920        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5921            return;
5922        }
5923        final int userId = UserHandle.getCallingUserId();
5924        if (DEBUG_PREFERRED) {
5925            Log.v(TAG, "setLastChosenActivity intent=" + intent
5926                + " resolvedType=" + resolvedType
5927                + " flags=" + flags
5928                + " filter=" + filter
5929                + " match=" + match
5930                + " activity=" + activity);
5931            filter.dump(new PrintStreamPrinter(System.out), "    ");
5932        }
5933        intent.setComponent(null);
5934        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5935                userId);
5936        // Find any earlier preferred or last chosen entries and nuke them
5937        findPreferredActivity(intent, resolvedType,
5938                flags, query, 0, false, true, false, userId);
5939        // Add the new activity as the last chosen for this filter
5940        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5941                "Setting last chosen");
5942    }
5943
5944    @Override
5945    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5946        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5947            return null;
5948        }
5949        final int userId = UserHandle.getCallingUserId();
5950        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5951        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5952                userId);
5953        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5954                false, false, false, userId);
5955    }
5956
5957    /**
5958     * Returns whether or not instant apps have been disabled remotely.
5959     */
5960    private boolean areWebInstantAppsDisabled() {
5961        return mWebInstantAppsDisabled;
5962    }
5963
5964    private boolean isInstantAppResolutionAllowed(
5965            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5966            boolean skipPackageCheck) {
5967        if (mInstantAppResolverConnection == null) {
5968            return false;
5969        }
5970        if (mInstantAppInstallerActivity == null) {
5971            return false;
5972        }
5973        if (intent.getComponent() != null) {
5974            return false;
5975        }
5976        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5977            return false;
5978        }
5979        if (!skipPackageCheck && intent.getPackage() != null) {
5980            return false;
5981        }
5982        if (!intent.isWebIntent()) {
5983            // for non web intents, we should not resolve externally if an app already exists to
5984            // handle it or if the caller didn't explicitly request it.
5985            if ((resolvedActivities != null && resolvedActivities.size() != 0)
5986                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
5987                return false;
5988            }
5989        } else {
5990            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
5991                return false;
5992            } else if (areWebInstantAppsDisabled()) {
5993                return false;
5994            }
5995        }
5996        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5997        // Or if there's already an ephemeral app installed that handles the action
5998        synchronized (mPackages) {
5999            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6000            for (int n = 0; n < count; n++) {
6001                final ResolveInfo info = resolvedActivities.get(n);
6002                final String packageName = info.activityInfo.packageName;
6003                final PackageSetting ps = mSettings.mPackages.get(packageName);
6004                if (ps != null) {
6005                    // only check domain verification status if the app is not a browser
6006                    if (!info.handleAllWebDataURI) {
6007                        // Try to get the status from User settings first
6008                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6009                        final int status = (int) (packedStatus >> 32);
6010                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6011                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6012                            if (DEBUG_INSTANT) {
6013                                Slog.v(TAG, "DENY instant app;"
6014                                    + " pkg: " + packageName + ", status: " + status);
6015                            }
6016                            return false;
6017                        }
6018                    }
6019                    if (ps.getInstantApp(userId)) {
6020                        if (DEBUG_INSTANT) {
6021                            Slog.v(TAG, "DENY instant app installed;"
6022                                    + " pkg: " + packageName);
6023                        }
6024                        return false;
6025                    }
6026                }
6027            }
6028        }
6029        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6030        return true;
6031    }
6032
6033    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6034            Intent origIntent, String resolvedType, String callingPackage,
6035            Bundle verificationBundle, int userId) {
6036        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6037                new InstantAppRequest(responseObj, origIntent, resolvedType,
6038                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6039        mHandler.sendMessage(msg);
6040    }
6041
6042    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6043            int flags, List<ResolveInfo> query, int userId) {
6044        if (query != null) {
6045            final int N = query.size();
6046            if (N == 1) {
6047                return query.get(0);
6048            } else if (N > 1) {
6049                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6050                // If there is more than one activity with the same priority,
6051                // then let the user decide between them.
6052                ResolveInfo r0 = query.get(0);
6053                ResolveInfo r1 = query.get(1);
6054                if (DEBUG_INTENT_MATCHING || debug) {
6055                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6056                            + r1.activityInfo.name + "=" + r1.priority);
6057                }
6058                // If the first activity has a higher priority, or a different
6059                // default, then it is always desirable to pick it.
6060                if (r0.priority != r1.priority
6061                        || r0.preferredOrder != r1.preferredOrder
6062                        || r0.isDefault != r1.isDefault) {
6063                    return query.get(0);
6064                }
6065                // If we have saved a preference for a preferred activity for
6066                // this Intent, use that.
6067                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6068                        flags, query, r0.priority, true, false, debug, userId);
6069                if (ri != null) {
6070                    return ri;
6071                }
6072                // If we have an ephemeral app, use it
6073                for (int i = 0; i < N; i++) {
6074                    ri = query.get(i);
6075                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6076                        final String packageName = ri.activityInfo.packageName;
6077                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6078                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6079                        final int status = (int)(packedStatus >> 32);
6080                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6081                            return ri;
6082                        }
6083                    }
6084                }
6085                ri = new ResolveInfo(mResolveInfo);
6086                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6087                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6088                // If all of the options come from the same package, show the application's
6089                // label and icon instead of the generic resolver's.
6090                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6091                // and then throw away the ResolveInfo itself, meaning that the caller loses
6092                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6093                // a fallback for this case; we only set the target package's resources on
6094                // the ResolveInfo, not the ActivityInfo.
6095                final String intentPackage = intent.getPackage();
6096                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6097                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6098                    ri.resolvePackageName = intentPackage;
6099                    if (userNeedsBadging(userId)) {
6100                        ri.noResourceId = true;
6101                    } else {
6102                        ri.icon = appi.icon;
6103                    }
6104                    ri.iconResourceId = appi.icon;
6105                    ri.labelRes = appi.labelRes;
6106                }
6107                ri.activityInfo.applicationInfo = new ApplicationInfo(
6108                        ri.activityInfo.applicationInfo);
6109                if (userId != 0) {
6110                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6111                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6112                }
6113                // Make sure that the resolver is displayable in car mode
6114                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6115                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6116                return ri;
6117            }
6118        }
6119        return null;
6120    }
6121
6122    /**
6123     * Return true if the given list is not empty and all of its contents have
6124     * an activityInfo with the given package name.
6125     */
6126    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6127        if (ArrayUtils.isEmpty(list)) {
6128            return false;
6129        }
6130        for (int i = 0, N = list.size(); i < N; i++) {
6131            final ResolveInfo ri = list.get(i);
6132            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6133            if (ai == null || !packageName.equals(ai.packageName)) {
6134                return false;
6135            }
6136        }
6137        return true;
6138    }
6139
6140    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6141            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6142        final int N = query.size();
6143        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6144                .get(userId);
6145        // Get the list of persistent preferred activities that handle the intent
6146        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6147        List<PersistentPreferredActivity> pprefs = ppir != null
6148                ? ppir.queryIntent(intent, resolvedType,
6149                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6150                        userId)
6151                : null;
6152        if (pprefs != null && pprefs.size() > 0) {
6153            final int M = pprefs.size();
6154            for (int i=0; i<M; i++) {
6155                final PersistentPreferredActivity ppa = pprefs.get(i);
6156                if (DEBUG_PREFERRED || debug) {
6157                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6158                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6159                            + "\n  component=" + ppa.mComponent);
6160                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6161                }
6162                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6163                        flags | MATCH_DISABLED_COMPONENTS, userId);
6164                if (DEBUG_PREFERRED || debug) {
6165                    Slog.v(TAG, "Found persistent preferred activity:");
6166                    if (ai != null) {
6167                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6168                    } else {
6169                        Slog.v(TAG, "  null");
6170                    }
6171                }
6172                if (ai == null) {
6173                    // This previously registered persistent preferred activity
6174                    // component is no longer known. Ignore it and do NOT remove it.
6175                    continue;
6176                }
6177                for (int j=0; j<N; j++) {
6178                    final ResolveInfo ri = query.get(j);
6179                    if (!ri.activityInfo.applicationInfo.packageName
6180                            .equals(ai.applicationInfo.packageName)) {
6181                        continue;
6182                    }
6183                    if (!ri.activityInfo.name.equals(ai.name)) {
6184                        continue;
6185                    }
6186                    //  Found a persistent preference that can handle the intent.
6187                    if (DEBUG_PREFERRED || debug) {
6188                        Slog.v(TAG, "Returning persistent preferred activity: " +
6189                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6190                    }
6191                    return ri;
6192                }
6193            }
6194        }
6195        return null;
6196    }
6197
6198    // TODO: handle preferred activities missing while user has amnesia
6199    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6200            List<ResolveInfo> query, int priority, boolean always,
6201            boolean removeMatches, boolean debug, int userId) {
6202        if (!sUserManager.exists(userId)) return null;
6203        final int callingUid = Binder.getCallingUid();
6204        flags = updateFlagsForResolve(
6205                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6206        intent = updateIntentForResolve(intent);
6207        // writer
6208        synchronized (mPackages) {
6209            // Try to find a matching persistent preferred activity.
6210            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6211                    debug, userId);
6212
6213            // If a persistent preferred activity matched, use it.
6214            if (pri != null) {
6215                return pri;
6216            }
6217
6218            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6219            // Get the list of preferred activities that handle the intent
6220            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6221            List<PreferredActivity> prefs = pir != null
6222                    ? pir.queryIntent(intent, resolvedType,
6223                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6224                            userId)
6225                    : null;
6226            if (prefs != null && prefs.size() > 0) {
6227                boolean changed = false;
6228                try {
6229                    // First figure out how good the original match set is.
6230                    // We will only allow preferred activities that came
6231                    // from the same match quality.
6232                    int match = 0;
6233
6234                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6235
6236                    final int N = query.size();
6237                    for (int j=0; j<N; j++) {
6238                        final ResolveInfo ri = query.get(j);
6239                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6240                                + ": 0x" + Integer.toHexString(match));
6241                        if (ri.match > match) {
6242                            match = ri.match;
6243                        }
6244                    }
6245
6246                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6247                            + Integer.toHexString(match));
6248
6249                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6250                    final int M = prefs.size();
6251                    for (int i=0; i<M; i++) {
6252                        final PreferredActivity pa = prefs.get(i);
6253                        if (DEBUG_PREFERRED || debug) {
6254                            Slog.v(TAG, "Checking PreferredActivity ds="
6255                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6256                                    + "\n  component=" + pa.mPref.mComponent);
6257                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6258                        }
6259                        if (pa.mPref.mMatch != match) {
6260                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6261                                    + Integer.toHexString(pa.mPref.mMatch));
6262                            continue;
6263                        }
6264                        // If it's not an "always" type preferred activity and that's what we're
6265                        // looking for, skip it.
6266                        if (always && !pa.mPref.mAlways) {
6267                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6268                            continue;
6269                        }
6270                        final ActivityInfo ai = getActivityInfo(
6271                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6272                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6273                                userId);
6274                        if (DEBUG_PREFERRED || debug) {
6275                            Slog.v(TAG, "Found preferred activity:");
6276                            if (ai != null) {
6277                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6278                            } else {
6279                                Slog.v(TAG, "  null");
6280                            }
6281                        }
6282                        if (ai == null) {
6283                            // This previously registered preferred activity
6284                            // component is no longer known.  Most likely an update
6285                            // to the app was installed and in the new version this
6286                            // component no longer exists.  Clean it up by removing
6287                            // it from the preferred activities list, and skip it.
6288                            Slog.w(TAG, "Removing dangling preferred activity: "
6289                                    + pa.mPref.mComponent);
6290                            pir.removeFilter(pa);
6291                            changed = true;
6292                            continue;
6293                        }
6294                        for (int j=0; j<N; j++) {
6295                            final ResolveInfo ri = query.get(j);
6296                            if (!ri.activityInfo.applicationInfo.packageName
6297                                    .equals(ai.applicationInfo.packageName)) {
6298                                continue;
6299                            }
6300                            if (!ri.activityInfo.name.equals(ai.name)) {
6301                                continue;
6302                            }
6303
6304                            if (removeMatches) {
6305                                pir.removeFilter(pa);
6306                                changed = true;
6307                                if (DEBUG_PREFERRED) {
6308                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6309                                }
6310                                break;
6311                            }
6312
6313                            // Okay we found a previously set preferred or last chosen app.
6314                            // If the result set is different from when this
6315                            // was created, and is not a subset of the preferred set, we need to
6316                            // clear it and re-ask the user their preference, if we're looking for
6317                            // an "always" type entry.
6318                            if (always && !pa.mPref.sameSet(query)) {
6319                                if (pa.mPref.isSuperset(query)) {
6320                                    // some components of the set are no longer present in
6321                                    // the query, but the preferred activity can still be reused
6322                                    if (DEBUG_PREFERRED) {
6323                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6324                                                + " still valid as only non-preferred components"
6325                                                + " were removed for " + intent + " type "
6326                                                + resolvedType);
6327                                    }
6328                                    // remove obsolete components and re-add the up-to-date filter
6329                                    PreferredActivity freshPa = new PreferredActivity(pa,
6330                                            pa.mPref.mMatch,
6331                                            pa.mPref.discardObsoleteComponents(query),
6332                                            pa.mPref.mComponent,
6333                                            pa.mPref.mAlways);
6334                                    pir.removeFilter(pa);
6335                                    pir.addFilter(freshPa);
6336                                    changed = true;
6337                                } else {
6338                                    Slog.i(TAG,
6339                                            "Result set changed, dropping preferred activity for "
6340                                                    + intent + " type " + resolvedType);
6341                                    if (DEBUG_PREFERRED) {
6342                                        Slog.v(TAG, "Removing preferred activity since set changed "
6343                                                + pa.mPref.mComponent);
6344                                    }
6345                                    pir.removeFilter(pa);
6346                                    // Re-add the filter as a "last chosen" entry (!always)
6347                                    PreferredActivity lastChosen = new PreferredActivity(
6348                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6349                                    pir.addFilter(lastChosen);
6350                                    changed = true;
6351                                    return null;
6352                                }
6353                            }
6354
6355                            // Yay! Either the set matched or we're looking for the last chosen
6356                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6357                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6358                            return ri;
6359                        }
6360                    }
6361                } finally {
6362                    if (changed) {
6363                        if (DEBUG_PREFERRED) {
6364                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6365                        }
6366                        scheduleWritePackageRestrictionsLocked(userId);
6367                    }
6368                }
6369            }
6370        }
6371        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6372        return null;
6373    }
6374
6375    /*
6376     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6377     */
6378    @Override
6379    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6380            int targetUserId) {
6381        mContext.enforceCallingOrSelfPermission(
6382                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6383        List<CrossProfileIntentFilter> matches =
6384                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6385        if (matches != null) {
6386            int size = matches.size();
6387            for (int i = 0; i < size; i++) {
6388                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6389            }
6390        }
6391        if (intent.hasWebURI()) {
6392            // cross-profile app linking works only towards the parent.
6393            final int callingUid = Binder.getCallingUid();
6394            final UserInfo parent = getProfileParent(sourceUserId);
6395            synchronized(mPackages) {
6396                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6397                        false /*includeInstantApps*/);
6398                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6399                        intent, resolvedType, flags, sourceUserId, parent.id);
6400                return xpDomainInfo != null;
6401            }
6402        }
6403        return false;
6404    }
6405
6406    private UserInfo getProfileParent(int userId) {
6407        final long identity = Binder.clearCallingIdentity();
6408        try {
6409            return sUserManager.getProfileParent(userId);
6410        } finally {
6411            Binder.restoreCallingIdentity(identity);
6412        }
6413    }
6414
6415    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6416            String resolvedType, int userId) {
6417        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6418        if (resolver != null) {
6419            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6420        }
6421        return null;
6422    }
6423
6424    @Override
6425    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6426            String resolvedType, int flags, int userId) {
6427        try {
6428            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6429
6430            return new ParceledListSlice<>(
6431                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6432        } finally {
6433            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6434        }
6435    }
6436
6437    /**
6438     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6439     * instant, returns {@code null}.
6440     */
6441    private String getInstantAppPackageName(int callingUid) {
6442        synchronized (mPackages) {
6443            // If the caller is an isolated app use the owner's uid for the lookup.
6444            if (Process.isIsolated(callingUid)) {
6445                callingUid = mIsolatedOwners.get(callingUid);
6446            }
6447            final int appId = UserHandle.getAppId(callingUid);
6448            final Object obj = mSettings.getUserIdLPr(appId);
6449            if (obj instanceof PackageSetting) {
6450                final PackageSetting ps = (PackageSetting) obj;
6451                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6452                return isInstantApp ? ps.pkg.packageName : null;
6453            }
6454        }
6455        return null;
6456    }
6457
6458    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6459            String resolvedType, int flags, int userId) {
6460        return queryIntentActivitiesInternal(
6461                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6462                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6463    }
6464
6465    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6466            String resolvedType, int flags, int filterCallingUid, int userId,
6467            boolean resolveForStart, boolean allowDynamicSplits) {
6468        if (!sUserManager.exists(userId)) return Collections.emptyList();
6469        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6470        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6471                false /* requireFullPermission */, false /* checkShell */,
6472                "query intent activities");
6473        final String pkgName = intent.getPackage();
6474        ComponentName comp = intent.getComponent();
6475        if (comp == null) {
6476            if (intent.getSelector() != null) {
6477                intent = intent.getSelector();
6478                comp = intent.getComponent();
6479            }
6480        }
6481
6482        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6483                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6484        if (comp != null) {
6485            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6486            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6487            if (ai != null) {
6488                // When specifying an explicit component, we prevent the activity from being
6489                // used when either 1) the calling package is normal and the activity is within
6490                // an ephemeral application or 2) the calling package is ephemeral and the
6491                // activity is not visible to ephemeral applications.
6492                final boolean matchInstantApp =
6493                        (flags & PackageManager.MATCH_INSTANT) != 0;
6494                final boolean matchVisibleToInstantAppOnly =
6495                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6496                final boolean matchExplicitlyVisibleOnly =
6497                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6498                final boolean isCallerInstantApp =
6499                        instantAppPkgName != null;
6500                final boolean isTargetSameInstantApp =
6501                        comp.getPackageName().equals(instantAppPkgName);
6502                final boolean isTargetInstantApp =
6503                        (ai.applicationInfo.privateFlags
6504                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6505                final boolean isTargetVisibleToInstantApp =
6506                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6507                final boolean isTargetExplicitlyVisibleToInstantApp =
6508                        isTargetVisibleToInstantApp
6509                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6510                final boolean isTargetHiddenFromInstantApp =
6511                        !isTargetVisibleToInstantApp
6512                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6513                final boolean blockResolution =
6514                        !isTargetSameInstantApp
6515                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6516                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6517                                        && isTargetHiddenFromInstantApp));
6518                if (!blockResolution) {
6519                    final ResolveInfo ri = new ResolveInfo();
6520                    ri.activityInfo = ai;
6521                    list.add(ri);
6522                }
6523            }
6524            return applyPostResolutionFilter(
6525                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6526        }
6527
6528        // reader
6529        boolean sortResult = false;
6530        boolean addInstant = false;
6531        List<ResolveInfo> result;
6532        synchronized (mPackages) {
6533            if (pkgName == null) {
6534                List<CrossProfileIntentFilter> matchingFilters =
6535                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6536                // Check for results that need to skip the current profile.
6537                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6538                        resolvedType, flags, userId);
6539                if (xpResolveInfo != null) {
6540                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6541                    xpResult.add(xpResolveInfo);
6542                    return applyPostResolutionFilter(
6543                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6544                            allowDynamicSplits, filterCallingUid, userId, intent);
6545                }
6546
6547                // Check for results in the current profile.
6548                result = filterIfNotSystemUser(mActivities.queryIntent(
6549                        intent, resolvedType, flags, userId), userId);
6550                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6551                        false /*skipPackageCheck*/);
6552                // Check for cross profile results.
6553                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6554                xpResolveInfo = queryCrossProfileIntents(
6555                        matchingFilters, intent, resolvedType, flags, userId,
6556                        hasNonNegativePriorityResult);
6557                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6558                    boolean isVisibleToUser = filterIfNotSystemUser(
6559                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6560                    if (isVisibleToUser) {
6561                        result.add(xpResolveInfo);
6562                        sortResult = true;
6563                    }
6564                }
6565                if (intent.hasWebURI()) {
6566                    CrossProfileDomainInfo xpDomainInfo = null;
6567                    final UserInfo parent = getProfileParent(userId);
6568                    if (parent != null) {
6569                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6570                                flags, userId, parent.id);
6571                    }
6572                    if (xpDomainInfo != null) {
6573                        if (xpResolveInfo != null) {
6574                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6575                            // in the result.
6576                            result.remove(xpResolveInfo);
6577                        }
6578                        if (result.size() == 0 && !addInstant) {
6579                            // No result in current profile, but found candidate in parent user.
6580                            // And we are not going to add emphemeral app, so we can return the
6581                            // result straight away.
6582                            result.add(xpDomainInfo.resolveInfo);
6583                            return applyPostResolutionFilter(result, instantAppPkgName,
6584                                    allowDynamicSplits, filterCallingUid, userId, intent);
6585                        }
6586                    } else if (result.size() <= 1 && !addInstant) {
6587                        // No result in parent user and <= 1 result in current profile, and we
6588                        // are not going to add emphemeral app, so we can return the result without
6589                        // further processing.
6590                        return applyPostResolutionFilter(result, instantAppPkgName,
6591                                allowDynamicSplits, filterCallingUid, userId, intent);
6592                    }
6593                    // We have more than one candidate (combining results from current and parent
6594                    // profile), so we need filtering and sorting.
6595                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6596                            intent, flags, result, xpDomainInfo, userId);
6597                    sortResult = true;
6598                }
6599            } else {
6600                final PackageParser.Package pkg = mPackages.get(pkgName);
6601                result = null;
6602                if (pkg != null) {
6603                    result = filterIfNotSystemUser(
6604                            mActivities.queryIntentForPackage(
6605                                    intent, resolvedType, flags, pkg.activities, userId),
6606                            userId);
6607                }
6608                if (result == null || result.size() == 0) {
6609                    // the caller wants to resolve for a particular package; however, there
6610                    // were no installed results, so, try to find an ephemeral result
6611                    addInstant = isInstantAppResolutionAllowed(
6612                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6613                    if (result == null) {
6614                        result = new ArrayList<>();
6615                    }
6616                }
6617            }
6618        }
6619        if (addInstant) {
6620            result = maybeAddInstantAppInstaller(
6621                    result, intent, resolvedType, flags, userId, resolveForStart);
6622        }
6623        if (sortResult) {
6624            Collections.sort(result, mResolvePrioritySorter);
6625        }
6626        return applyPostResolutionFilter(
6627                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6628    }
6629
6630    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6631            String resolvedType, int flags, int userId, boolean resolveForStart) {
6632        // first, check to see if we've got an instant app already installed
6633        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6634        ResolveInfo localInstantApp = null;
6635        boolean blockResolution = false;
6636        if (!alreadyResolvedLocally) {
6637            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6638                    flags
6639                        | PackageManager.GET_RESOLVED_FILTER
6640                        | PackageManager.MATCH_INSTANT
6641                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6642                    userId);
6643            for (int i = instantApps.size() - 1; i >= 0; --i) {
6644                final ResolveInfo info = instantApps.get(i);
6645                final String packageName = info.activityInfo.packageName;
6646                final PackageSetting ps = mSettings.mPackages.get(packageName);
6647                if (ps.getInstantApp(userId)) {
6648                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6649                    final int status = (int)(packedStatus >> 32);
6650                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6651                        // there's a local instant application installed, but, the user has
6652                        // chosen to never use it; skip resolution and don't acknowledge
6653                        // an instant application is even available
6654                        if (DEBUG_INSTANT) {
6655                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6656                        }
6657                        blockResolution = true;
6658                        break;
6659                    } else {
6660                        // we have a locally installed instant application; skip resolution
6661                        // but acknowledge there's an instant application available
6662                        if (DEBUG_INSTANT) {
6663                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6664                        }
6665                        localInstantApp = info;
6666                        break;
6667                    }
6668                }
6669            }
6670        }
6671        // no app installed, let's see if one's available
6672        AuxiliaryResolveInfo auxiliaryResponse = null;
6673        if (!blockResolution) {
6674            if (localInstantApp == null) {
6675                // we don't have an instant app locally, resolve externally
6676                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6677                final InstantAppRequest requestObject = new InstantAppRequest(
6678                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6679                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6680                        resolveForStart);
6681                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6682                        mInstantAppResolverConnection, requestObject);
6683                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6684            } else {
6685                // we have an instant application locally, but, we can't admit that since
6686                // callers shouldn't be able to determine prior browsing. create a dummy
6687                // auxiliary response so the downstream code behaves as if there's an
6688                // instant application available externally. when it comes time to start
6689                // the instant application, we'll do the right thing.
6690                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6691                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6692                                        ai.packageName, ai.versionCode, null /* splitName */);
6693            }
6694        }
6695        if (intent.isWebIntent() && auxiliaryResponse == null) {
6696            return result;
6697        }
6698        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6699        if (ps == null) {
6700            return result;
6701        }
6702        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6703        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6704                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6705        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6706                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6707        // add a non-generic filter
6708        ephemeralInstaller.filter = new IntentFilter();
6709        if (intent.getAction() != null) {
6710            ephemeralInstaller.filter.addAction(intent.getAction());
6711        }
6712        if (intent.getData() != null && intent.getData().getPath() != null) {
6713            ephemeralInstaller.filter.addDataPath(
6714                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6715        }
6716        ephemeralInstaller.isInstantAppAvailable = true;
6717        // make sure this resolver is the default
6718        ephemeralInstaller.isDefault = true;
6719        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6720        if (DEBUG_INSTANT) {
6721            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6722        }
6723
6724        result.add(ephemeralInstaller);
6725        return result;
6726    }
6727
6728    private static class CrossProfileDomainInfo {
6729        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6730        ResolveInfo resolveInfo;
6731        /* Best domain verification status of the activities found in the other profile */
6732        int bestDomainVerificationStatus;
6733    }
6734
6735    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6736            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6737        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6738                sourceUserId)) {
6739            return null;
6740        }
6741        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6742                resolvedType, flags, parentUserId);
6743
6744        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6745            return null;
6746        }
6747        CrossProfileDomainInfo result = null;
6748        int size = resultTargetUser.size();
6749        for (int i = 0; i < size; i++) {
6750            ResolveInfo riTargetUser = resultTargetUser.get(i);
6751            // Intent filter verification is only for filters that specify a host. So don't return
6752            // those that handle all web uris.
6753            if (riTargetUser.handleAllWebDataURI) {
6754                continue;
6755            }
6756            String packageName = riTargetUser.activityInfo.packageName;
6757            PackageSetting ps = mSettings.mPackages.get(packageName);
6758            if (ps == null) {
6759                continue;
6760            }
6761            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6762            int status = (int)(verificationState >> 32);
6763            if (result == null) {
6764                result = new CrossProfileDomainInfo();
6765                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6766                        sourceUserId, parentUserId);
6767                result.bestDomainVerificationStatus = status;
6768            } else {
6769                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6770                        result.bestDomainVerificationStatus);
6771            }
6772        }
6773        // Don't consider matches with status NEVER across profiles.
6774        if (result != null && result.bestDomainVerificationStatus
6775                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6776            return null;
6777        }
6778        return result;
6779    }
6780
6781    /**
6782     * Verification statuses are ordered from the worse to the best, except for
6783     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6784     */
6785    private int bestDomainVerificationStatus(int status1, int status2) {
6786        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6787            return status2;
6788        }
6789        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6790            return status1;
6791        }
6792        return (int) MathUtils.max(status1, status2);
6793    }
6794
6795    private boolean isUserEnabled(int userId) {
6796        long callingId = Binder.clearCallingIdentity();
6797        try {
6798            UserInfo userInfo = sUserManager.getUserInfo(userId);
6799            return userInfo != null && userInfo.isEnabled();
6800        } finally {
6801            Binder.restoreCallingIdentity(callingId);
6802        }
6803    }
6804
6805    /**
6806     * Filter out activities with systemUserOnly flag set, when current user is not System.
6807     *
6808     * @return filtered list
6809     */
6810    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6811        if (userId == UserHandle.USER_SYSTEM) {
6812            return resolveInfos;
6813        }
6814        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6815            ResolveInfo info = resolveInfos.get(i);
6816            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6817                resolveInfos.remove(i);
6818            }
6819        }
6820        return resolveInfos;
6821    }
6822
6823    /**
6824     * Filters out ephemeral activities.
6825     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6826     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6827     *
6828     * @param resolveInfos The pre-filtered list of resolved activities
6829     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6830     *          is performed.
6831     * @param intent
6832     * @return A filtered list of resolved activities.
6833     */
6834    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6835            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6836            Intent intent) {
6837        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6838        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6839            final ResolveInfo info = resolveInfos.get(i);
6840            // remove locally resolved instant app web results when disabled
6841            if (info.isInstantAppAvailable && blockInstant) {
6842                resolveInfos.remove(i);
6843                continue;
6844            }
6845            // allow activities that are defined in the provided package
6846            if (allowDynamicSplits
6847                    && info.activityInfo != null
6848                    && info.activityInfo.splitName != null
6849                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6850                            info.activityInfo.splitName)) {
6851                if (mInstantAppInstallerActivity == null) {
6852                    if (DEBUG_INSTALL) {
6853                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6854                    }
6855                    resolveInfos.remove(i);
6856                    continue;
6857                }
6858                // requested activity is defined in a split that hasn't been installed yet.
6859                // add the installer to the resolve list
6860                if (DEBUG_INSTALL) {
6861                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6862                }
6863                final ResolveInfo installerInfo = new ResolveInfo(
6864                        mInstantAppInstallerInfo);
6865                final ComponentName installFailureActivity = findInstallFailureActivity(
6866                        info.activityInfo.packageName,  filterCallingUid, userId);
6867                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6868                        installFailureActivity,
6869                        info.activityInfo.packageName,
6870                        info.activityInfo.applicationInfo.versionCode,
6871                        info.activityInfo.splitName);
6872                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6873                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6874                // add a non-generic filter
6875                installerInfo.filter = new IntentFilter();
6876
6877                // This resolve info may appear in the chooser UI, so let us make it
6878                // look as the one it replaces as far as the user is concerned which
6879                // requires loading the correct label and icon for the resolve info.
6880                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6881                installerInfo.labelRes = info.resolveLabelResId();
6882                installerInfo.icon = info.resolveIconResId();
6883
6884                // propagate priority/preferred order/default
6885                installerInfo.priority = info.priority;
6886                installerInfo.preferredOrder = info.preferredOrder;
6887                installerInfo.isDefault = info.isDefault;
6888                installerInfo.isInstantAppAvailable = true;
6889                resolveInfos.set(i, installerInfo);
6890                continue;
6891            }
6892            // caller is a full app, don't need to apply any other filtering
6893            if (ephemeralPkgName == null) {
6894                continue;
6895            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6896                // caller is same app; don't need to apply any other filtering
6897                continue;
6898            }
6899            // allow activities that have been explicitly exposed to ephemeral apps
6900            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6901            if (!isEphemeralApp
6902                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6903                continue;
6904            }
6905            resolveInfos.remove(i);
6906        }
6907        return resolveInfos;
6908    }
6909
6910    /**
6911     * Returns the activity component that can handle install failures.
6912     * <p>By default, the instant application installer handles failures. However, an
6913     * application may want to handle failures on its own. Applications do this by
6914     * creating an activity with an intent filter that handles the action
6915     * {@link Intent#ACTION_INSTALL_FAILURE}.
6916     */
6917    private @Nullable ComponentName findInstallFailureActivity(
6918            String packageName, int filterCallingUid, int userId) {
6919        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6920        failureActivityIntent.setPackage(packageName);
6921        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6922        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6923                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6924                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6925        final int NR = result.size();
6926        if (NR > 0) {
6927            for (int i = 0; i < NR; i++) {
6928                final ResolveInfo info = result.get(i);
6929                if (info.activityInfo.splitName != null) {
6930                    continue;
6931                }
6932                return new ComponentName(packageName, info.activityInfo.name);
6933            }
6934        }
6935        return null;
6936    }
6937
6938    /**
6939     * @param resolveInfos list of resolve infos in descending priority order
6940     * @return if the list contains a resolve info with non-negative priority
6941     */
6942    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6943        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6944    }
6945
6946    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6947            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6948            int userId) {
6949        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6950
6951        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6952            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6953                    candidates.size());
6954        }
6955
6956        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6957        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6958        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6959        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6960        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6961        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6962
6963        synchronized (mPackages) {
6964            final int count = candidates.size();
6965            // First, try to use linked apps. Partition the candidates into four lists:
6966            // one for the final results, one for the "do not use ever", one for "undefined status"
6967            // and finally one for "browser app type".
6968            for (int n=0; n<count; n++) {
6969                ResolveInfo info = candidates.get(n);
6970                String packageName = info.activityInfo.packageName;
6971                PackageSetting ps = mSettings.mPackages.get(packageName);
6972                if (ps != null) {
6973                    // Add to the special match all list (Browser use case)
6974                    if (info.handleAllWebDataURI) {
6975                        matchAllList.add(info);
6976                        continue;
6977                    }
6978                    // Try to get the status from User settings first
6979                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6980                    int status = (int)(packedStatus >> 32);
6981                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6982                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6983                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6984                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6985                                    + " : linkgen=" + linkGeneration);
6986                        }
6987                        // Use link-enabled generation as preferredOrder, i.e.
6988                        // prefer newly-enabled over earlier-enabled.
6989                        info.preferredOrder = linkGeneration;
6990                        alwaysList.add(info);
6991                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6992                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6993                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6994                        }
6995                        neverList.add(info);
6996                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6997                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6998                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6999                        }
7000                        alwaysAskList.add(info);
7001                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7002                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7003                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7004                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7005                        }
7006                        undefinedList.add(info);
7007                    }
7008                }
7009            }
7010
7011            // We'll want to include browser possibilities in a few cases
7012            boolean includeBrowser = false;
7013
7014            // First try to add the "always" resolution(s) for the current user, if any
7015            if (alwaysList.size() > 0) {
7016                result.addAll(alwaysList);
7017            } else {
7018                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7019                result.addAll(undefinedList);
7020                // Maybe add one for the other profile.
7021                if (xpDomainInfo != null && (
7022                        xpDomainInfo.bestDomainVerificationStatus
7023                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7024                    result.add(xpDomainInfo.resolveInfo);
7025                }
7026                includeBrowser = true;
7027            }
7028
7029            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7030            // If there were 'always' entries their preferred order has been set, so we also
7031            // back that off to make the alternatives equivalent
7032            if (alwaysAskList.size() > 0) {
7033                for (ResolveInfo i : result) {
7034                    i.preferredOrder = 0;
7035                }
7036                result.addAll(alwaysAskList);
7037                includeBrowser = true;
7038            }
7039
7040            if (includeBrowser) {
7041                // Also add browsers (all of them or only the default one)
7042                if (DEBUG_DOMAIN_VERIFICATION) {
7043                    Slog.v(TAG, "   ...including browsers in candidate set");
7044                }
7045                if ((matchFlags & MATCH_ALL) != 0) {
7046                    result.addAll(matchAllList);
7047                } else {
7048                    // Browser/generic handling case.  If there's a default browser, go straight
7049                    // to that (but only if there is no other higher-priority match).
7050                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7051                    int maxMatchPrio = 0;
7052                    ResolveInfo defaultBrowserMatch = null;
7053                    final int numCandidates = matchAllList.size();
7054                    for (int n = 0; n < numCandidates; n++) {
7055                        ResolveInfo info = matchAllList.get(n);
7056                        // track the highest overall match priority...
7057                        if (info.priority > maxMatchPrio) {
7058                            maxMatchPrio = info.priority;
7059                        }
7060                        // ...and the highest-priority default browser match
7061                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7062                            if (defaultBrowserMatch == null
7063                                    || (defaultBrowserMatch.priority < info.priority)) {
7064                                if (debug) {
7065                                    Slog.v(TAG, "Considering default browser match " + info);
7066                                }
7067                                defaultBrowserMatch = info;
7068                            }
7069                        }
7070                    }
7071                    if (defaultBrowserMatch != null
7072                            && defaultBrowserMatch.priority >= maxMatchPrio
7073                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7074                    {
7075                        if (debug) {
7076                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7077                        }
7078                        result.add(defaultBrowserMatch);
7079                    } else {
7080                        result.addAll(matchAllList);
7081                    }
7082                }
7083
7084                // If there is nothing selected, add all candidates and remove the ones that the user
7085                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7086                if (result.size() == 0) {
7087                    result.addAll(candidates);
7088                    result.removeAll(neverList);
7089                }
7090            }
7091        }
7092        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7093            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7094                    result.size());
7095            for (ResolveInfo info : result) {
7096                Slog.v(TAG, "  + " + info.activityInfo);
7097            }
7098        }
7099        return result;
7100    }
7101
7102    // Returns a packed value as a long:
7103    //
7104    // high 'int'-sized word: link status: undefined/ask/never/always.
7105    // low 'int'-sized word: relative priority among 'always' results.
7106    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7107        long result = ps.getDomainVerificationStatusForUser(userId);
7108        // if none available, get the master status
7109        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7110            if (ps.getIntentFilterVerificationInfo() != null) {
7111                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7112            }
7113        }
7114        return result;
7115    }
7116
7117    private ResolveInfo querySkipCurrentProfileIntents(
7118            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7119            int flags, int sourceUserId) {
7120        if (matchingFilters != null) {
7121            int size = matchingFilters.size();
7122            for (int i = 0; i < size; i ++) {
7123                CrossProfileIntentFilter filter = matchingFilters.get(i);
7124                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7125                    // Checking if there are activities in the target user that can handle the
7126                    // intent.
7127                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7128                            resolvedType, flags, sourceUserId);
7129                    if (resolveInfo != null) {
7130                        return resolveInfo;
7131                    }
7132                }
7133            }
7134        }
7135        return null;
7136    }
7137
7138    // Return matching ResolveInfo in target user if any.
7139    private ResolveInfo queryCrossProfileIntents(
7140            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7141            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7142        if (matchingFilters != null) {
7143            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7144            // match the same intent. For performance reasons, it is better not to
7145            // run queryIntent twice for the same userId
7146            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7147            int size = matchingFilters.size();
7148            for (int i = 0; i < size; i++) {
7149                CrossProfileIntentFilter filter = matchingFilters.get(i);
7150                int targetUserId = filter.getTargetUserId();
7151                boolean skipCurrentProfile =
7152                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7153                boolean skipCurrentProfileIfNoMatchFound =
7154                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7155                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7156                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7157                    // Checking if there are activities in the target user that can handle the
7158                    // intent.
7159                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7160                            resolvedType, flags, sourceUserId);
7161                    if (resolveInfo != null) return resolveInfo;
7162                    alreadyTriedUserIds.put(targetUserId, true);
7163                }
7164            }
7165        }
7166        return null;
7167    }
7168
7169    /**
7170     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7171     * will forward the intent to the filter's target user.
7172     * Otherwise, returns null.
7173     */
7174    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7175            String resolvedType, int flags, int sourceUserId) {
7176        int targetUserId = filter.getTargetUserId();
7177        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7178                resolvedType, flags, targetUserId);
7179        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7180            // If all the matches in the target profile are suspended, return null.
7181            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7182                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7183                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7184                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7185                            targetUserId);
7186                }
7187            }
7188        }
7189        return null;
7190    }
7191
7192    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7193            int sourceUserId, int targetUserId) {
7194        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7195        long ident = Binder.clearCallingIdentity();
7196        boolean targetIsProfile;
7197        try {
7198            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7199        } finally {
7200            Binder.restoreCallingIdentity(ident);
7201        }
7202        String className;
7203        if (targetIsProfile) {
7204            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7205        } else {
7206            className = FORWARD_INTENT_TO_PARENT;
7207        }
7208        ComponentName forwardingActivityComponentName = new ComponentName(
7209                mAndroidApplication.packageName, className);
7210        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7211                sourceUserId);
7212        if (!targetIsProfile) {
7213            forwardingActivityInfo.showUserIcon = targetUserId;
7214            forwardingResolveInfo.noResourceId = true;
7215        }
7216        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7217        forwardingResolveInfo.priority = 0;
7218        forwardingResolveInfo.preferredOrder = 0;
7219        forwardingResolveInfo.match = 0;
7220        forwardingResolveInfo.isDefault = true;
7221        forwardingResolveInfo.filter = filter;
7222        forwardingResolveInfo.targetUserId = targetUserId;
7223        return forwardingResolveInfo;
7224    }
7225
7226    @Override
7227    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7228            Intent[] specifics, String[] specificTypes, Intent intent,
7229            String resolvedType, int flags, int userId) {
7230        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7231                specificTypes, intent, resolvedType, flags, userId));
7232    }
7233
7234    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7235            Intent[] specifics, String[] specificTypes, Intent intent,
7236            String resolvedType, int flags, int userId) {
7237        if (!sUserManager.exists(userId)) return Collections.emptyList();
7238        final int callingUid = Binder.getCallingUid();
7239        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7240                false /*includeInstantApps*/);
7241        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7242                false /*requireFullPermission*/, false /*checkShell*/,
7243                "query intent activity options");
7244        final String resultsAction = intent.getAction();
7245
7246        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7247                | PackageManager.GET_RESOLVED_FILTER, userId);
7248
7249        if (DEBUG_INTENT_MATCHING) {
7250            Log.v(TAG, "Query " + intent + ": " + results);
7251        }
7252
7253        int specificsPos = 0;
7254        int N;
7255
7256        // todo: note that the algorithm used here is O(N^2).  This
7257        // isn't a problem in our current environment, but if we start running
7258        // into situations where we have more than 5 or 10 matches then this
7259        // should probably be changed to something smarter...
7260
7261        // First we go through and resolve each of the specific items
7262        // that were supplied, taking care of removing any corresponding
7263        // duplicate items in the generic resolve list.
7264        if (specifics != null) {
7265            for (int i=0; i<specifics.length; i++) {
7266                final Intent sintent = specifics[i];
7267                if (sintent == null) {
7268                    continue;
7269                }
7270
7271                if (DEBUG_INTENT_MATCHING) {
7272                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7273                }
7274
7275                String action = sintent.getAction();
7276                if (resultsAction != null && resultsAction.equals(action)) {
7277                    // If this action was explicitly requested, then don't
7278                    // remove things that have it.
7279                    action = null;
7280                }
7281
7282                ResolveInfo ri = null;
7283                ActivityInfo ai = null;
7284
7285                ComponentName comp = sintent.getComponent();
7286                if (comp == null) {
7287                    ri = resolveIntent(
7288                        sintent,
7289                        specificTypes != null ? specificTypes[i] : null,
7290                            flags, userId);
7291                    if (ri == null) {
7292                        continue;
7293                    }
7294                    if (ri == mResolveInfo) {
7295                        // ACK!  Must do something better with this.
7296                    }
7297                    ai = ri.activityInfo;
7298                    comp = new ComponentName(ai.applicationInfo.packageName,
7299                            ai.name);
7300                } else {
7301                    ai = getActivityInfo(comp, flags, userId);
7302                    if (ai == null) {
7303                        continue;
7304                    }
7305                }
7306
7307                // Look for any generic query activities that are duplicates
7308                // of this specific one, and remove them from the results.
7309                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7310                N = results.size();
7311                int j;
7312                for (j=specificsPos; j<N; j++) {
7313                    ResolveInfo sri = results.get(j);
7314                    if ((sri.activityInfo.name.equals(comp.getClassName())
7315                            && sri.activityInfo.applicationInfo.packageName.equals(
7316                                    comp.getPackageName()))
7317                        || (action != null && sri.filter.matchAction(action))) {
7318                        results.remove(j);
7319                        if (DEBUG_INTENT_MATCHING) Log.v(
7320                            TAG, "Removing duplicate item from " + j
7321                            + " due to specific " + specificsPos);
7322                        if (ri == null) {
7323                            ri = sri;
7324                        }
7325                        j--;
7326                        N--;
7327                    }
7328                }
7329
7330                // Add this specific item to its proper place.
7331                if (ri == null) {
7332                    ri = new ResolveInfo();
7333                    ri.activityInfo = ai;
7334                }
7335                results.add(specificsPos, ri);
7336                ri.specificIndex = i;
7337                specificsPos++;
7338            }
7339        }
7340
7341        // Now we go through the remaining generic results and remove any
7342        // duplicate actions that are found here.
7343        N = results.size();
7344        for (int i=specificsPos; i<N-1; i++) {
7345            final ResolveInfo rii = results.get(i);
7346            if (rii.filter == null) {
7347                continue;
7348            }
7349
7350            // Iterate over all of the actions of this result's intent
7351            // filter...  typically this should be just one.
7352            final Iterator<String> it = rii.filter.actionsIterator();
7353            if (it == null) {
7354                continue;
7355            }
7356            while (it.hasNext()) {
7357                final String action = it.next();
7358                if (resultsAction != null && resultsAction.equals(action)) {
7359                    // If this action was explicitly requested, then don't
7360                    // remove things that have it.
7361                    continue;
7362                }
7363                for (int j=i+1; j<N; j++) {
7364                    final ResolveInfo rij = results.get(j);
7365                    if (rij.filter != null && rij.filter.hasAction(action)) {
7366                        results.remove(j);
7367                        if (DEBUG_INTENT_MATCHING) Log.v(
7368                            TAG, "Removing duplicate item from " + j
7369                            + " due to action " + action + " at " + i);
7370                        j--;
7371                        N--;
7372                    }
7373                }
7374            }
7375
7376            // If the caller didn't request filter information, drop it now
7377            // so we don't have to marshall/unmarshall it.
7378            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7379                rii.filter = null;
7380            }
7381        }
7382
7383        // Filter out the caller activity if so requested.
7384        if (caller != null) {
7385            N = results.size();
7386            for (int i=0; i<N; i++) {
7387                ActivityInfo ainfo = results.get(i).activityInfo;
7388                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7389                        && caller.getClassName().equals(ainfo.name)) {
7390                    results.remove(i);
7391                    break;
7392                }
7393            }
7394        }
7395
7396        // If the caller didn't request filter information,
7397        // drop them now so we don't have to
7398        // marshall/unmarshall it.
7399        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7400            N = results.size();
7401            for (int i=0; i<N; i++) {
7402                results.get(i).filter = null;
7403            }
7404        }
7405
7406        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7407        return results;
7408    }
7409
7410    @Override
7411    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7412            String resolvedType, int flags, int userId) {
7413        return new ParceledListSlice<>(
7414                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7415                        false /*allowDynamicSplits*/));
7416    }
7417
7418    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7419            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7420        if (!sUserManager.exists(userId)) return Collections.emptyList();
7421        final int callingUid = Binder.getCallingUid();
7422        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7423                false /*requireFullPermission*/, false /*checkShell*/,
7424                "query intent receivers");
7425        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7426        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7427                false /*includeInstantApps*/);
7428        ComponentName comp = intent.getComponent();
7429        if (comp == null) {
7430            if (intent.getSelector() != null) {
7431                intent = intent.getSelector();
7432                comp = intent.getComponent();
7433            }
7434        }
7435        if (comp != null) {
7436            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7437            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7438            if (ai != null) {
7439                // When specifying an explicit component, we prevent the activity from being
7440                // used when either 1) the calling package is normal and the activity is within
7441                // an instant application or 2) the calling package is ephemeral and the
7442                // activity is not visible to instant applications.
7443                final boolean matchInstantApp =
7444                        (flags & PackageManager.MATCH_INSTANT) != 0;
7445                final boolean matchVisibleToInstantAppOnly =
7446                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7447                final boolean matchExplicitlyVisibleOnly =
7448                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7449                final boolean isCallerInstantApp =
7450                        instantAppPkgName != null;
7451                final boolean isTargetSameInstantApp =
7452                        comp.getPackageName().equals(instantAppPkgName);
7453                final boolean isTargetInstantApp =
7454                        (ai.applicationInfo.privateFlags
7455                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7456                final boolean isTargetVisibleToInstantApp =
7457                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7458                final boolean isTargetExplicitlyVisibleToInstantApp =
7459                        isTargetVisibleToInstantApp
7460                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7461                final boolean isTargetHiddenFromInstantApp =
7462                        !isTargetVisibleToInstantApp
7463                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7464                final boolean blockResolution =
7465                        !isTargetSameInstantApp
7466                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7467                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7468                                        && isTargetHiddenFromInstantApp));
7469                if (!blockResolution) {
7470                    ResolveInfo ri = new ResolveInfo();
7471                    ri.activityInfo = ai;
7472                    list.add(ri);
7473                }
7474            }
7475            return applyPostResolutionFilter(
7476                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7477        }
7478
7479        // reader
7480        synchronized (mPackages) {
7481            String pkgName = intent.getPackage();
7482            if (pkgName == null) {
7483                final List<ResolveInfo> result =
7484                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7485                return applyPostResolutionFilter(
7486                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7487            }
7488            final PackageParser.Package pkg = mPackages.get(pkgName);
7489            if (pkg != null) {
7490                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7491                        intent, resolvedType, flags, pkg.receivers, userId);
7492                return applyPostResolutionFilter(
7493                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7494            }
7495            return Collections.emptyList();
7496        }
7497    }
7498
7499    @Override
7500    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7501        final int callingUid = Binder.getCallingUid();
7502        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7503    }
7504
7505    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7506            int userId, int callingUid) {
7507        if (!sUserManager.exists(userId)) return null;
7508        flags = updateFlagsForResolve(
7509                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7510        List<ResolveInfo> query = queryIntentServicesInternal(
7511                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7512        if (query != null) {
7513            if (query.size() >= 1) {
7514                // If there is more than one service with the same priority,
7515                // just arbitrarily pick the first one.
7516                return query.get(0);
7517            }
7518        }
7519        return null;
7520    }
7521
7522    @Override
7523    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7524            String resolvedType, int flags, int userId) {
7525        final int callingUid = Binder.getCallingUid();
7526        return new ParceledListSlice<>(queryIntentServicesInternal(
7527                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7528    }
7529
7530    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7531            String resolvedType, int flags, int userId, int callingUid,
7532            boolean includeInstantApps) {
7533        if (!sUserManager.exists(userId)) return Collections.emptyList();
7534        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7535                false /*requireFullPermission*/, false /*checkShell*/,
7536                "query intent receivers");
7537        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7538        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7539        ComponentName comp = intent.getComponent();
7540        if (comp == null) {
7541            if (intent.getSelector() != null) {
7542                intent = intent.getSelector();
7543                comp = intent.getComponent();
7544            }
7545        }
7546        if (comp != null) {
7547            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7548            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7549            if (si != null) {
7550                // When specifying an explicit component, we prevent the service from being
7551                // used when either 1) the service is in an instant application and the
7552                // caller is not the same instant application or 2) the calling package is
7553                // ephemeral and the activity is not visible to ephemeral applications.
7554                final boolean matchInstantApp =
7555                        (flags & PackageManager.MATCH_INSTANT) != 0;
7556                final boolean matchVisibleToInstantAppOnly =
7557                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7558                final boolean isCallerInstantApp =
7559                        instantAppPkgName != null;
7560                final boolean isTargetSameInstantApp =
7561                        comp.getPackageName().equals(instantAppPkgName);
7562                final boolean isTargetInstantApp =
7563                        (si.applicationInfo.privateFlags
7564                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7565                final boolean isTargetHiddenFromInstantApp =
7566                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7567                final boolean blockResolution =
7568                        !isTargetSameInstantApp
7569                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7570                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7571                                        && isTargetHiddenFromInstantApp));
7572                if (!blockResolution) {
7573                    final ResolveInfo ri = new ResolveInfo();
7574                    ri.serviceInfo = si;
7575                    list.add(ri);
7576                }
7577            }
7578            return list;
7579        }
7580
7581        // reader
7582        synchronized (mPackages) {
7583            String pkgName = intent.getPackage();
7584            if (pkgName == null) {
7585                return applyPostServiceResolutionFilter(
7586                        mServices.queryIntent(intent, resolvedType, flags, userId),
7587                        instantAppPkgName);
7588            }
7589            final PackageParser.Package pkg = mPackages.get(pkgName);
7590            if (pkg != null) {
7591                return applyPostServiceResolutionFilter(
7592                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7593                                userId),
7594                        instantAppPkgName);
7595            }
7596            return Collections.emptyList();
7597        }
7598    }
7599
7600    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7601            String instantAppPkgName) {
7602        if (instantAppPkgName == null) {
7603            return resolveInfos;
7604        }
7605        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7606            final ResolveInfo info = resolveInfos.get(i);
7607            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7608            // allow services that are defined in the provided package
7609            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7610                if (info.serviceInfo.splitName != null
7611                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7612                                info.serviceInfo.splitName)) {
7613                    // requested service is defined in a split that hasn't been installed yet.
7614                    // add the installer to the resolve list
7615                    if (DEBUG_INSTANT) {
7616                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7617                    }
7618                    final ResolveInfo installerInfo = new ResolveInfo(
7619                            mInstantAppInstallerInfo);
7620                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7621                            null /* installFailureActivity */,
7622                            info.serviceInfo.packageName,
7623                            info.serviceInfo.applicationInfo.versionCode,
7624                            info.serviceInfo.splitName);
7625                    // make sure this resolver is the default
7626                    installerInfo.isDefault = true;
7627                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7628                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7629                    // add a non-generic filter
7630                    installerInfo.filter = new IntentFilter();
7631                    // load resources from the correct package
7632                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7633                    resolveInfos.set(i, installerInfo);
7634                }
7635                continue;
7636            }
7637            // allow services that have been explicitly exposed to ephemeral apps
7638            if (!isEphemeralApp
7639                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7640                continue;
7641            }
7642            resolveInfos.remove(i);
7643        }
7644        return resolveInfos;
7645    }
7646
7647    @Override
7648    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7649            String resolvedType, int flags, int userId) {
7650        return new ParceledListSlice<>(
7651                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7652    }
7653
7654    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7655            Intent intent, String resolvedType, int flags, int userId) {
7656        if (!sUserManager.exists(userId)) return Collections.emptyList();
7657        final int callingUid = Binder.getCallingUid();
7658        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7659        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7660                false /*includeInstantApps*/);
7661        ComponentName comp = intent.getComponent();
7662        if (comp == null) {
7663            if (intent.getSelector() != null) {
7664                intent = intent.getSelector();
7665                comp = intent.getComponent();
7666            }
7667        }
7668        if (comp != null) {
7669            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7670            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7671            if (pi != null) {
7672                // When specifying an explicit component, we prevent the provider from being
7673                // used when either 1) the provider is in an instant application and the
7674                // caller is not the same instant application or 2) the calling package is an
7675                // instant application and the provider is not visible to instant applications.
7676                final boolean matchInstantApp =
7677                        (flags & PackageManager.MATCH_INSTANT) != 0;
7678                final boolean matchVisibleToInstantAppOnly =
7679                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7680                final boolean isCallerInstantApp =
7681                        instantAppPkgName != null;
7682                final boolean isTargetSameInstantApp =
7683                        comp.getPackageName().equals(instantAppPkgName);
7684                final boolean isTargetInstantApp =
7685                        (pi.applicationInfo.privateFlags
7686                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7687                final boolean isTargetHiddenFromInstantApp =
7688                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7689                final boolean blockResolution =
7690                        !isTargetSameInstantApp
7691                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7692                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7693                                        && isTargetHiddenFromInstantApp));
7694                if (!blockResolution) {
7695                    final ResolveInfo ri = new ResolveInfo();
7696                    ri.providerInfo = pi;
7697                    list.add(ri);
7698                }
7699            }
7700            return list;
7701        }
7702
7703        // reader
7704        synchronized (mPackages) {
7705            String pkgName = intent.getPackage();
7706            if (pkgName == null) {
7707                return applyPostContentProviderResolutionFilter(
7708                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7709                        instantAppPkgName);
7710            }
7711            final PackageParser.Package pkg = mPackages.get(pkgName);
7712            if (pkg != null) {
7713                return applyPostContentProviderResolutionFilter(
7714                        mProviders.queryIntentForPackage(
7715                        intent, resolvedType, flags, pkg.providers, userId),
7716                        instantAppPkgName);
7717            }
7718            return Collections.emptyList();
7719        }
7720    }
7721
7722    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7723            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7724        if (instantAppPkgName == null) {
7725            return resolveInfos;
7726        }
7727        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7728            final ResolveInfo info = resolveInfos.get(i);
7729            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7730            // allow providers that are defined in the provided package
7731            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7732                if (info.providerInfo.splitName != null
7733                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7734                                info.providerInfo.splitName)) {
7735                    // requested provider is defined in a split that hasn't been installed yet.
7736                    // add the installer to the resolve list
7737                    if (DEBUG_INSTANT) {
7738                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7739                    }
7740                    final ResolveInfo installerInfo = new ResolveInfo(
7741                            mInstantAppInstallerInfo);
7742                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7743                            null /*failureActivity*/,
7744                            info.providerInfo.packageName,
7745                            info.providerInfo.applicationInfo.versionCode,
7746                            info.providerInfo.splitName);
7747                    // make sure this resolver is the default
7748                    installerInfo.isDefault = true;
7749                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7750                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7751                    // add a non-generic filter
7752                    installerInfo.filter = new IntentFilter();
7753                    // load resources from the correct package
7754                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7755                    resolveInfos.set(i, installerInfo);
7756                }
7757                continue;
7758            }
7759            // allow providers that have been explicitly exposed to instant applications
7760            if (!isEphemeralApp
7761                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7762                continue;
7763            }
7764            resolveInfos.remove(i);
7765        }
7766        return resolveInfos;
7767    }
7768
7769    @Override
7770    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7771        final int callingUid = Binder.getCallingUid();
7772        if (getInstantAppPackageName(callingUid) != null) {
7773            return ParceledListSlice.emptyList();
7774        }
7775        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7776        flags = updateFlagsForPackage(flags, userId, null);
7777        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7778        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7779                true /* requireFullPermission */, false /* checkShell */,
7780                "get installed packages");
7781
7782        // writer
7783        synchronized (mPackages) {
7784            ArrayList<PackageInfo> list;
7785            if (listUninstalled) {
7786                list = new ArrayList<>(mSettings.mPackages.size());
7787                for (PackageSetting ps : mSettings.mPackages.values()) {
7788                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7789                        continue;
7790                    }
7791                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7792                        continue;
7793                    }
7794                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7795                    if (pi != null) {
7796                        list.add(pi);
7797                    }
7798                }
7799            } else {
7800                list = new ArrayList<>(mPackages.size());
7801                for (PackageParser.Package p : mPackages.values()) {
7802                    final PackageSetting ps = (PackageSetting) p.mExtras;
7803                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7804                        continue;
7805                    }
7806                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7807                        continue;
7808                    }
7809                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7810                            p.mExtras, flags, userId);
7811                    if (pi != null) {
7812                        list.add(pi);
7813                    }
7814                }
7815            }
7816
7817            return new ParceledListSlice<>(list);
7818        }
7819    }
7820
7821    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7822            String[] permissions, boolean[] tmp, int flags, int userId) {
7823        int numMatch = 0;
7824        final PermissionsState permissionsState = ps.getPermissionsState();
7825        for (int i=0; i<permissions.length; i++) {
7826            final String permission = permissions[i];
7827            if (permissionsState.hasPermission(permission, userId)) {
7828                tmp[i] = true;
7829                numMatch++;
7830            } else {
7831                tmp[i] = false;
7832            }
7833        }
7834        if (numMatch == 0) {
7835            return;
7836        }
7837        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7838
7839        // The above might return null in cases of uninstalled apps or install-state
7840        // skew across users/profiles.
7841        if (pi != null) {
7842            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7843                if (numMatch == permissions.length) {
7844                    pi.requestedPermissions = permissions;
7845                } else {
7846                    pi.requestedPermissions = new String[numMatch];
7847                    numMatch = 0;
7848                    for (int i=0; i<permissions.length; i++) {
7849                        if (tmp[i]) {
7850                            pi.requestedPermissions[numMatch] = permissions[i];
7851                            numMatch++;
7852                        }
7853                    }
7854                }
7855            }
7856            list.add(pi);
7857        }
7858    }
7859
7860    @Override
7861    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7862            String[] permissions, int flags, int userId) {
7863        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7864        flags = updateFlagsForPackage(flags, userId, permissions);
7865        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7866                true /* requireFullPermission */, false /* checkShell */,
7867                "get packages holding permissions");
7868        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7869
7870        // writer
7871        synchronized (mPackages) {
7872            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7873            boolean[] tmpBools = new boolean[permissions.length];
7874            if (listUninstalled) {
7875                for (PackageSetting ps : mSettings.mPackages.values()) {
7876                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7877                            userId);
7878                }
7879            } else {
7880                for (PackageParser.Package pkg : mPackages.values()) {
7881                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7882                    if (ps != null) {
7883                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7884                                userId);
7885                    }
7886                }
7887            }
7888
7889            return new ParceledListSlice<PackageInfo>(list);
7890        }
7891    }
7892
7893    @Override
7894    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7895        final int callingUid = Binder.getCallingUid();
7896        if (getInstantAppPackageName(callingUid) != null) {
7897            return ParceledListSlice.emptyList();
7898        }
7899        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7900        flags = updateFlagsForApplication(flags, userId, null);
7901        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7902
7903        // writer
7904        synchronized (mPackages) {
7905            ArrayList<ApplicationInfo> list;
7906            if (listUninstalled) {
7907                list = new ArrayList<>(mSettings.mPackages.size());
7908                for (PackageSetting ps : mSettings.mPackages.values()) {
7909                    ApplicationInfo ai;
7910                    int effectiveFlags = flags;
7911                    if (ps.isSystem()) {
7912                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7913                    }
7914                    if (ps.pkg != null) {
7915                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7916                            continue;
7917                        }
7918                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7919                            continue;
7920                        }
7921                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7922                                ps.readUserState(userId), userId);
7923                        if (ai != null) {
7924                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7925                        }
7926                    } else {
7927                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7928                        // and already converts to externally visible package name
7929                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7930                                callingUid, effectiveFlags, userId);
7931                    }
7932                    if (ai != null) {
7933                        list.add(ai);
7934                    }
7935                }
7936            } else {
7937                list = new ArrayList<>(mPackages.size());
7938                for (PackageParser.Package p : mPackages.values()) {
7939                    if (p.mExtras != null) {
7940                        PackageSetting ps = (PackageSetting) p.mExtras;
7941                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7942                            continue;
7943                        }
7944                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7945                            continue;
7946                        }
7947                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7948                                ps.readUserState(userId), userId);
7949                        if (ai != null) {
7950                            ai.packageName = resolveExternalPackageNameLPr(p);
7951                            list.add(ai);
7952                        }
7953                    }
7954                }
7955            }
7956
7957            return new ParceledListSlice<>(list);
7958        }
7959    }
7960
7961    @Override
7962    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7963        if (HIDE_EPHEMERAL_APIS) {
7964            return null;
7965        }
7966        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7967            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7968                    "getEphemeralApplications");
7969        }
7970        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7971                true /* requireFullPermission */, false /* checkShell */,
7972                "getEphemeralApplications");
7973        synchronized (mPackages) {
7974            List<InstantAppInfo> instantApps = mInstantAppRegistry
7975                    .getInstantAppsLPr(userId);
7976            if (instantApps != null) {
7977                return new ParceledListSlice<>(instantApps);
7978            }
7979        }
7980        return null;
7981    }
7982
7983    @Override
7984    public boolean isInstantApp(String packageName, int userId) {
7985        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7986                true /* requireFullPermission */, false /* checkShell */,
7987                "isInstantApp");
7988        if (HIDE_EPHEMERAL_APIS) {
7989            return false;
7990        }
7991
7992        synchronized (mPackages) {
7993            int callingUid = Binder.getCallingUid();
7994            if (Process.isIsolated(callingUid)) {
7995                callingUid = mIsolatedOwners.get(callingUid);
7996            }
7997            final PackageSetting ps = mSettings.mPackages.get(packageName);
7998            PackageParser.Package pkg = mPackages.get(packageName);
7999            final boolean returnAllowed =
8000                    ps != null
8001                    && (isCallerSameApp(packageName, callingUid)
8002                            || canViewInstantApps(callingUid, userId)
8003                            || mInstantAppRegistry.isInstantAccessGranted(
8004                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8005            if (returnAllowed) {
8006                return ps.getInstantApp(userId);
8007            }
8008        }
8009        return false;
8010    }
8011
8012    @Override
8013    public byte[] getInstantAppCookie(String packageName, int userId) {
8014        if (HIDE_EPHEMERAL_APIS) {
8015            return null;
8016        }
8017
8018        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8019                true /* requireFullPermission */, false /* checkShell */,
8020                "getInstantAppCookie");
8021        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8022            return null;
8023        }
8024        synchronized (mPackages) {
8025            return mInstantAppRegistry.getInstantAppCookieLPw(
8026                    packageName, userId);
8027        }
8028    }
8029
8030    @Override
8031    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8032        if (HIDE_EPHEMERAL_APIS) {
8033            return true;
8034        }
8035
8036        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8037                true /* requireFullPermission */, true /* checkShell */,
8038                "setInstantAppCookie");
8039        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8040            return false;
8041        }
8042        synchronized (mPackages) {
8043            return mInstantAppRegistry.setInstantAppCookieLPw(
8044                    packageName, cookie, userId);
8045        }
8046    }
8047
8048    @Override
8049    public Bitmap getInstantAppIcon(String packageName, int userId) {
8050        if (HIDE_EPHEMERAL_APIS) {
8051            return null;
8052        }
8053
8054        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8055            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8056                    "getInstantAppIcon");
8057        }
8058        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8059                true /* requireFullPermission */, false /* checkShell */,
8060                "getInstantAppIcon");
8061
8062        synchronized (mPackages) {
8063            return mInstantAppRegistry.getInstantAppIconLPw(
8064                    packageName, userId);
8065        }
8066    }
8067
8068    private boolean isCallerSameApp(String packageName, int uid) {
8069        PackageParser.Package pkg = mPackages.get(packageName);
8070        return pkg != null
8071                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8072    }
8073
8074    @Override
8075    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8076        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8077            return ParceledListSlice.emptyList();
8078        }
8079        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8080    }
8081
8082    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8083        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8084
8085        // reader
8086        synchronized (mPackages) {
8087            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8088            final int userId = UserHandle.getCallingUserId();
8089            while (i.hasNext()) {
8090                final PackageParser.Package p = i.next();
8091                if (p.applicationInfo == null) continue;
8092
8093                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8094                        && !p.applicationInfo.isDirectBootAware();
8095                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8096                        && p.applicationInfo.isDirectBootAware();
8097
8098                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8099                        && (!mSafeMode || isSystemApp(p))
8100                        && (matchesUnaware || matchesAware)) {
8101                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8102                    if (ps != null) {
8103                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8104                                ps.readUserState(userId), userId);
8105                        if (ai != null) {
8106                            finalList.add(ai);
8107                        }
8108                    }
8109                }
8110            }
8111        }
8112
8113        return finalList;
8114    }
8115
8116    @Override
8117    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8118        return resolveContentProviderInternal(name, flags, userId);
8119    }
8120
8121    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8122        if (!sUserManager.exists(userId)) return null;
8123        flags = updateFlagsForComponent(flags, userId, name);
8124        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8125        // reader
8126        synchronized (mPackages) {
8127            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8128            PackageSetting ps = provider != null
8129                    ? mSettings.mPackages.get(provider.owner.packageName)
8130                    : null;
8131            if (ps != null) {
8132                final boolean isInstantApp = ps.getInstantApp(userId);
8133                // normal application; filter out instant application provider
8134                if (instantAppPkgName == null && isInstantApp) {
8135                    return null;
8136                }
8137                // instant application; filter out other instant applications
8138                if (instantAppPkgName != null
8139                        && isInstantApp
8140                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8141                    return null;
8142                }
8143                // instant application; filter out non-exposed provider
8144                if (instantAppPkgName != null
8145                        && !isInstantApp
8146                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8147                    return null;
8148                }
8149                // provider not enabled
8150                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8151                    return null;
8152                }
8153                return PackageParser.generateProviderInfo(
8154                        provider, flags, ps.readUserState(userId), userId);
8155            }
8156            return null;
8157        }
8158    }
8159
8160    /**
8161     * @deprecated
8162     */
8163    @Deprecated
8164    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8165        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8166            return;
8167        }
8168        // reader
8169        synchronized (mPackages) {
8170            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8171                    .entrySet().iterator();
8172            final int userId = UserHandle.getCallingUserId();
8173            while (i.hasNext()) {
8174                Map.Entry<String, PackageParser.Provider> entry = i.next();
8175                PackageParser.Provider p = entry.getValue();
8176                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8177
8178                if (ps != null && p.syncable
8179                        && (!mSafeMode || (p.info.applicationInfo.flags
8180                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8181                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8182                            ps.readUserState(userId), userId);
8183                    if (info != null) {
8184                        outNames.add(entry.getKey());
8185                        outInfo.add(info);
8186                    }
8187                }
8188            }
8189        }
8190    }
8191
8192    @Override
8193    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8194            int uid, int flags, String metaDataKey) {
8195        final int callingUid = Binder.getCallingUid();
8196        final int userId = processName != null ? UserHandle.getUserId(uid)
8197                : UserHandle.getCallingUserId();
8198        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8199        flags = updateFlagsForComponent(flags, userId, processName);
8200        ArrayList<ProviderInfo> finalList = null;
8201        // reader
8202        synchronized (mPackages) {
8203            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8204            while (i.hasNext()) {
8205                final PackageParser.Provider p = i.next();
8206                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8207                if (ps != null && p.info.authority != null
8208                        && (processName == null
8209                                || (p.info.processName.equals(processName)
8210                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8211                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8212
8213                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8214                    // parameter.
8215                    if (metaDataKey != null
8216                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8217                        continue;
8218                    }
8219                    final ComponentName component =
8220                            new ComponentName(p.info.packageName, p.info.name);
8221                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8222                        continue;
8223                    }
8224                    if (finalList == null) {
8225                        finalList = new ArrayList<ProviderInfo>(3);
8226                    }
8227                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8228                            ps.readUserState(userId), userId);
8229                    if (info != null) {
8230                        finalList.add(info);
8231                    }
8232                }
8233            }
8234        }
8235
8236        if (finalList != null) {
8237            Collections.sort(finalList, mProviderInitOrderSorter);
8238            return new ParceledListSlice<ProviderInfo>(finalList);
8239        }
8240
8241        return ParceledListSlice.emptyList();
8242    }
8243
8244    @Override
8245    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8246        // reader
8247        synchronized (mPackages) {
8248            final int callingUid = Binder.getCallingUid();
8249            final int callingUserId = UserHandle.getUserId(callingUid);
8250            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8251            if (ps == null) return null;
8252            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8253                return null;
8254            }
8255            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8256            return PackageParser.generateInstrumentationInfo(i, flags);
8257        }
8258    }
8259
8260    @Override
8261    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8262            String targetPackage, int flags) {
8263        final int callingUid = Binder.getCallingUid();
8264        final int callingUserId = UserHandle.getUserId(callingUid);
8265        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8266        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8267            return ParceledListSlice.emptyList();
8268        }
8269        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8270    }
8271
8272    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8273            int flags) {
8274        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8275
8276        // reader
8277        synchronized (mPackages) {
8278            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8279            while (i.hasNext()) {
8280                final PackageParser.Instrumentation p = i.next();
8281                if (targetPackage == null
8282                        || targetPackage.equals(p.info.targetPackage)) {
8283                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8284                            flags);
8285                    if (ii != null) {
8286                        finalList.add(ii);
8287                    }
8288                }
8289            }
8290        }
8291
8292        return finalList;
8293    }
8294
8295    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8296        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8297        try {
8298            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8299        } finally {
8300            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8301        }
8302    }
8303
8304    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8305        final File[] files = scanDir.listFiles();
8306        if (ArrayUtils.isEmpty(files)) {
8307            Log.d(TAG, "No files in app dir " + scanDir);
8308            return;
8309        }
8310
8311        if (DEBUG_PACKAGE_SCANNING) {
8312            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8313                    + " flags=0x" + Integer.toHexString(parseFlags));
8314        }
8315        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8316                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8317                mParallelPackageParserCallback)) {
8318            // Submit files for parsing in parallel
8319            int fileCount = 0;
8320            for (File file : files) {
8321                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8322                        && !PackageInstallerService.isStageName(file.getName());
8323                if (!isPackage) {
8324                    // Ignore entries which are not packages
8325                    continue;
8326                }
8327                parallelPackageParser.submit(file, parseFlags);
8328                fileCount++;
8329            }
8330
8331            // Process results one by one
8332            for (; fileCount > 0; fileCount--) {
8333                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8334                Throwable throwable = parseResult.throwable;
8335                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8336
8337                if (throwable == null) {
8338                    // TODO(toddke): move lower in the scan chain
8339                    // Static shared libraries have synthetic package names
8340                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8341                        renameStaticSharedLibraryPackage(parseResult.pkg);
8342                    }
8343                    try {
8344                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8345                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8346                                    currentTime, null);
8347                        }
8348                    } catch (PackageManagerException e) {
8349                        errorCode = e.error;
8350                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8351                    }
8352                } else if (throwable instanceof PackageParser.PackageParserException) {
8353                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8354                            throwable;
8355                    errorCode = e.error;
8356                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8357                } else {
8358                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8359                            + parseResult.scanFile, throwable);
8360                }
8361
8362                // Delete invalid userdata apps
8363                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8364                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8365                    logCriticalInfo(Log.WARN,
8366                            "Deleting invalid package at " + parseResult.scanFile);
8367                    removeCodePathLI(parseResult.scanFile);
8368                }
8369            }
8370        }
8371    }
8372
8373    public static void reportSettingsProblem(int priority, String msg) {
8374        logCriticalInfo(priority, msg);
8375    }
8376
8377    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8378            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8379        // When upgrading from pre-N MR1, verify the package time stamp using the package
8380        // directory and not the APK file.
8381        final long lastModifiedTime = mIsPreNMR1Upgrade
8382                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8383        if (ps != null && !forceCollect
8384                && ps.codePathString.equals(pkg.codePath)
8385                && ps.timeStamp == lastModifiedTime
8386                && !isCompatSignatureUpdateNeeded(pkg)
8387                && !isRecoverSignatureUpdateNeeded(pkg)) {
8388            if (ps.signatures.mSigningDetails.signatures != null
8389                    && ps.signatures.mSigningDetails.signatures.length != 0
8390                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8391                            != SignatureSchemeVersion.UNKNOWN) {
8392                // Optimization: reuse the existing cached signing data
8393                // if the package appears to be unchanged.
8394                pkg.mSigningDetails =
8395                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8396                return;
8397            }
8398
8399            Slog.w(TAG, "PackageSetting for " + ps.name
8400                    + " is missing signatures.  Collecting certs again to recover them.");
8401        } else {
8402            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8403                    (forceCollect ? " (forced)" : ""));
8404        }
8405
8406        try {
8407            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8408            PackageParser.collectCertificates(pkg, skipVerify);
8409        } catch (PackageParserException e) {
8410            throw PackageManagerException.from(e);
8411        } finally {
8412            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8413        }
8414    }
8415
8416    /**
8417     *  Traces a package scan.
8418     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8419     */
8420    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8421            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8422        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8423        try {
8424            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8425        } finally {
8426            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8427        }
8428    }
8429
8430    /**
8431     *  Scans a package and returns the newly parsed package.
8432     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8433     */
8434    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8435            long currentTime, UserHandle user) throws PackageManagerException {
8436        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8437        PackageParser pp = new PackageParser();
8438        pp.setSeparateProcesses(mSeparateProcesses);
8439        pp.setOnlyCoreApps(mOnlyCore);
8440        pp.setDisplayMetrics(mMetrics);
8441        pp.setCallback(mPackageParserCallback);
8442
8443        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8444        final PackageParser.Package pkg;
8445        try {
8446            pkg = pp.parsePackage(scanFile, parseFlags);
8447        } catch (PackageParserException e) {
8448            throw PackageManagerException.from(e);
8449        } finally {
8450            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8451        }
8452
8453        // Static shared libraries have synthetic package names
8454        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8455            renameStaticSharedLibraryPackage(pkg);
8456        }
8457
8458        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8459    }
8460
8461    /**
8462     *  Scans a package and returns the newly parsed package.
8463     *  @throws PackageManagerException on a parse error.
8464     */
8465    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8466            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8467            @Nullable UserHandle user)
8468                    throws PackageManagerException {
8469        // If the package has children and this is the first dive in the function
8470        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8471        // packages (parent and children) would be successfully scanned before the
8472        // actual scan since scanning mutates internal state and we want to atomically
8473        // install the package and its children.
8474        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8475            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8476                scanFlags |= SCAN_CHECK_ONLY;
8477            }
8478        } else {
8479            scanFlags &= ~SCAN_CHECK_ONLY;
8480        }
8481
8482        // Scan the parent
8483        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8484                scanFlags, currentTime, user);
8485
8486        // Scan the children
8487        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8488        for (int i = 0; i < childCount; i++) {
8489            PackageParser.Package childPackage = pkg.childPackages.get(i);
8490            addForInitLI(childPackage, parseFlags, scanFlags,
8491                    currentTime, user);
8492        }
8493
8494
8495        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8496            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8497        }
8498
8499        return scannedPkg;
8500    }
8501
8502    /**
8503     * Returns if full apk verification can be skipped for the whole package, including the splits.
8504     */
8505    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8506        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8507            return false;
8508        }
8509        // TODO: Allow base and splits to be verified individually.
8510        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8511            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8512                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8513                    return false;
8514                }
8515            }
8516        }
8517        return true;
8518    }
8519
8520    /**
8521     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8522     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8523     * match one in a trusted source, and should be done separately.
8524     */
8525    private boolean canSkipFullApkVerification(String apkPath) {
8526        byte[] rootHashObserved = null;
8527        try {
8528            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8529            if (rootHashObserved == null) {
8530                return false;  // APK does not contain Merkle tree root hash.
8531            }
8532            synchronized (mInstallLock) {
8533                // Returns whether the observed root hash matches what kernel has.
8534                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8535                return true;
8536            }
8537        } catch (InstallerException | IOException | DigestException |
8538                NoSuchAlgorithmException e) {
8539            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8540        }
8541        return false;
8542    }
8543
8544    /**
8545     * Adds a new package to the internal data structures during platform initialization.
8546     * <p>After adding, the package is known to the system and available for querying.
8547     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8548     * etc...], additional checks are performed. Basic verification [such as ensuring
8549     * matching signatures, checking version codes, etc...] occurs if the package is
8550     * identical to a previously known package. If the package fails a signature check,
8551     * the version installed on /data will be removed. If the version of the new package
8552     * is less than or equal than the version on /data, it will be ignored.
8553     * <p>Regardless of the package location, the results are applied to the internal
8554     * structures and the package is made available to the rest of the system.
8555     * <p>NOTE: The return value should be removed. It's the passed in package object.
8556     */
8557    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8558            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8559            @Nullable UserHandle user)
8560                    throws PackageManagerException {
8561        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8562        final String renamedPkgName;
8563        final PackageSetting disabledPkgSetting;
8564        final boolean isSystemPkgUpdated;
8565        final boolean pkgAlreadyExists;
8566        PackageSetting pkgSetting;
8567
8568        // NOTE: installPackageLI() has the same code to setup the package's
8569        // application info. This probably should be done lower in the call
8570        // stack [such as scanPackageOnly()]. However, we verify the application
8571        // info prior to that [in scanPackageNew()] and thus have to setup
8572        // the application info early.
8573        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8574        pkg.setApplicationInfoCodePath(pkg.codePath);
8575        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8576        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8577        pkg.setApplicationInfoResourcePath(pkg.codePath);
8578        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8579        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8580
8581        synchronized (mPackages) {
8582            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8583            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8584            if (realPkgName != null) {
8585                ensurePackageRenamed(pkg, renamedPkgName);
8586            }
8587            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8588            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8589            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8590            pkgAlreadyExists = pkgSetting != null;
8591            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8592            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8593            isSystemPkgUpdated = disabledPkgSetting != null;
8594
8595            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8596                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8597            }
8598
8599            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8600                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8601                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8602                    : null;
8603            if (DEBUG_PACKAGE_SCANNING
8604                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8605                    && sharedUserSetting != null) {
8606                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8607                        + " (uid=" + sharedUserSetting.userId + "):"
8608                        + " packages=" + sharedUserSetting.packages);
8609            }
8610
8611            if (scanSystemPartition) {
8612                // Potentially prune child packages. If the application on the /system
8613                // partition has been updated via OTA, but, is still disabled by a
8614                // version on /data, cycle through all of its children packages and
8615                // remove children that are no longer defined.
8616                if (isSystemPkgUpdated) {
8617                    final int scannedChildCount = (pkg.childPackages != null)
8618                            ? pkg.childPackages.size() : 0;
8619                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8620                            ? disabledPkgSetting.childPackageNames.size() : 0;
8621                    for (int i = 0; i < disabledChildCount; i++) {
8622                        String disabledChildPackageName =
8623                                disabledPkgSetting.childPackageNames.get(i);
8624                        boolean disabledPackageAvailable = false;
8625                        for (int j = 0; j < scannedChildCount; j++) {
8626                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8627                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8628                                disabledPackageAvailable = true;
8629                                break;
8630                            }
8631                        }
8632                        if (!disabledPackageAvailable) {
8633                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8634                        }
8635                    }
8636                    // we're updating the disabled package, so, scan it as the package setting
8637                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8638                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8639                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8640                            (pkg == mPlatformPackage), user);
8641                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8642                }
8643            }
8644        }
8645
8646        final boolean newPkgChangedPaths =
8647                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8648        final boolean newPkgVersionGreater =
8649                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8650        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8651                && newPkgChangedPaths && newPkgVersionGreater;
8652        if (isSystemPkgBetter) {
8653            // The version of the application on /system is greater than the version on
8654            // /data. Switch back to the application on /system.
8655            // It's safe to assume the application on /system will correctly scan. If not,
8656            // there won't be a working copy of the application.
8657            synchronized (mPackages) {
8658                // just remove the loaded entries from package lists
8659                mPackages.remove(pkgSetting.name);
8660            }
8661
8662            logCriticalInfo(Log.WARN,
8663                    "System package updated;"
8664                    + " name: " + pkgSetting.name
8665                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8666                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8667
8668            final InstallArgs args = createInstallArgsForExisting(
8669                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8670                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8671            args.cleanUpResourcesLI();
8672            synchronized (mPackages) {
8673                mSettings.enableSystemPackageLPw(pkgSetting.name);
8674            }
8675        }
8676
8677        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8678            // The version of the application on the /system partition is less than or
8679            // equal to the version on the /data partition. Throw an exception and use
8680            // the application already installed on the /data partition.
8681            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8682                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8683                    + " better than this " + pkg.getLongVersionCode());
8684        }
8685
8686        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8687        // force re-collecting certificate.
8688        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8689                disabledPkgSetting);
8690        // Full APK verification can be skipped during certificate collection, only if the file is
8691        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8692        // cases, only data in Signing Block is verified instead of the whole file.
8693        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8694                (forceCollect && canSkipFullPackageVerification(pkg));
8695        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8696
8697        boolean shouldHideSystemApp = false;
8698        // A new application appeared on /system, but, we already have a copy of
8699        // the application installed on /data.
8700        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8701                && !pkgSetting.isSystem()) {
8702
8703            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8704                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8705                logCriticalInfo(Log.WARN,
8706                        "System package signature mismatch;"
8707                        + " name: " + pkgSetting.name);
8708                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8709                        "scanPackageInternalLI")) {
8710                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8711                }
8712                pkgSetting = null;
8713            } else if (newPkgVersionGreater) {
8714                // The application on /system is newer than the application on /data.
8715                // Simply remove the application on /data [keeping application data]
8716                // and replace it with the version on /system.
8717                logCriticalInfo(Log.WARN,
8718                        "System package enabled;"
8719                        + " name: " + pkgSetting.name
8720                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8721                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8722                InstallArgs args = createInstallArgsForExisting(
8723                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8724                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8725                synchronized (mInstallLock) {
8726                    args.cleanUpResourcesLI();
8727                }
8728            } else {
8729                // The application on /system is older than the application on /data. Hide
8730                // the application on /system and the version on /data will be scanned later
8731                // and re-added like an update.
8732                shouldHideSystemApp = true;
8733                logCriticalInfo(Log.INFO,
8734                        "System package disabled;"
8735                        + " name: " + pkgSetting.name
8736                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8737                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8738            }
8739        }
8740
8741        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8742                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8743
8744        if (shouldHideSystemApp) {
8745            synchronized (mPackages) {
8746                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8747            }
8748        }
8749        return scannedPkg;
8750    }
8751
8752    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8753        // Derive the new package synthetic package name
8754        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8755                + pkg.staticSharedLibVersion);
8756    }
8757
8758    private static String fixProcessName(String defProcessName,
8759            String processName) {
8760        if (processName == null) {
8761            return defProcessName;
8762        }
8763        return processName;
8764    }
8765
8766    /**
8767     * Enforces that only the system UID or root's UID can call a method exposed
8768     * via Binder.
8769     *
8770     * @param message used as message if SecurityException is thrown
8771     * @throws SecurityException if the caller is not system or root
8772     */
8773    private static final void enforceSystemOrRoot(String message) {
8774        final int uid = Binder.getCallingUid();
8775        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8776            throw new SecurityException(message);
8777        }
8778    }
8779
8780    @Override
8781    public void performFstrimIfNeeded() {
8782        enforceSystemOrRoot("Only the system can request fstrim");
8783
8784        // Before everything else, see whether we need to fstrim.
8785        try {
8786            IStorageManager sm = PackageHelper.getStorageManager();
8787            if (sm != null) {
8788                boolean doTrim = false;
8789                final long interval = android.provider.Settings.Global.getLong(
8790                        mContext.getContentResolver(),
8791                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8792                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8793                if (interval > 0) {
8794                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8795                    if (timeSinceLast > interval) {
8796                        doTrim = true;
8797                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8798                                + "; running immediately");
8799                    }
8800                }
8801                if (doTrim) {
8802                    final boolean dexOptDialogShown;
8803                    synchronized (mPackages) {
8804                        dexOptDialogShown = mDexOptDialogShown;
8805                    }
8806                    if (!isFirstBoot() && dexOptDialogShown) {
8807                        try {
8808                            ActivityManager.getService().showBootMessage(
8809                                    mContext.getResources().getString(
8810                                            R.string.android_upgrading_fstrim), true);
8811                        } catch (RemoteException e) {
8812                        }
8813                    }
8814                    sm.runMaintenance();
8815                }
8816            } else {
8817                Slog.e(TAG, "storageManager service unavailable!");
8818            }
8819        } catch (RemoteException e) {
8820            // Can't happen; StorageManagerService is local
8821        }
8822    }
8823
8824    @Override
8825    public void updatePackagesIfNeeded() {
8826        enforceSystemOrRoot("Only the system can request package update");
8827
8828        // We need to re-extract after an OTA.
8829        boolean causeUpgrade = isUpgrade();
8830
8831        // First boot or factory reset.
8832        // Note: we also handle devices that are upgrading to N right now as if it is their
8833        //       first boot, as they do not have profile data.
8834        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8835
8836        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8837        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8838
8839        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8840            return;
8841        }
8842
8843        List<PackageParser.Package> pkgs;
8844        synchronized (mPackages) {
8845            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8846        }
8847
8848        final long startTime = System.nanoTime();
8849        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8850                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8851                    false /* bootComplete */);
8852
8853        final int elapsedTimeSeconds =
8854                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8855
8856        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8857        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8858        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8859        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8860        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8861    }
8862
8863    /*
8864     * Return the prebuilt profile path given a package base code path.
8865     */
8866    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8867        return pkg.baseCodePath + ".prof";
8868    }
8869
8870    /**
8871     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8872     * containing statistics about the invocation. The array consists of three elements,
8873     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8874     * and {@code numberOfPackagesFailed}.
8875     */
8876    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8877            final String compilerFilter, boolean bootComplete) {
8878
8879        int numberOfPackagesVisited = 0;
8880        int numberOfPackagesOptimized = 0;
8881        int numberOfPackagesSkipped = 0;
8882        int numberOfPackagesFailed = 0;
8883        final int numberOfPackagesToDexopt = pkgs.size();
8884
8885        for (PackageParser.Package pkg : pkgs) {
8886            numberOfPackagesVisited++;
8887
8888            boolean useProfileForDexopt = false;
8889
8890            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8891                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8892                // that are already compiled.
8893                File profileFile = new File(getPrebuildProfilePath(pkg));
8894                // Copy profile if it exists.
8895                if (profileFile.exists()) {
8896                    try {
8897                        // We could also do this lazily before calling dexopt in
8898                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8899                        // is that we don't have a good way to say "do this only once".
8900                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8901                                pkg.applicationInfo.uid, pkg.packageName,
8902                                ArtManager.getProfileName(null))) {
8903                            Log.e(TAG, "Installer failed to copy system profile!");
8904                        } else {
8905                            // Disabled as this causes speed-profile compilation during first boot
8906                            // even if things are already compiled.
8907                            // useProfileForDexopt = true;
8908                        }
8909                    } catch (Exception e) {
8910                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8911                                e);
8912                    }
8913                } else {
8914                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8915                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8916                    // minimize the number off apps being speed-profile compiled during first boot.
8917                    // The other paths will not change the filter.
8918                    if (disabledPs != null && disabledPs.pkg.isStub) {
8919                        // The package is the stub one, remove the stub suffix to get the normal
8920                        // package and APK names.
8921                        String systemProfilePath =
8922                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8923                        profileFile = new File(systemProfilePath);
8924                        // If we have a profile for a compressed APK, copy it to the reference
8925                        // location.
8926                        // Note that copying the profile here will cause it to override the
8927                        // reference profile every OTA even though the existing reference profile
8928                        // may have more data. We can't copy during decompression since the
8929                        // directories are not set up at that point.
8930                        if (profileFile.exists()) {
8931                            try {
8932                                // We could also do this lazily before calling dexopt in
8933                                // PackageDexOptimizer to prevent this happening on first boot. The
8934                                // issue is that we don't have a good way to say "do this only
8935                                // once".
8936                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8937                                        pkg.applicationInfo.uid, pkg.packageName,
8938                                        ArtManager.getProfileName(null))) {
8939                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8940                                } else {
8941                                    useProfileForDexopt = true;
8942                                }
8943                            } catch (Exception e) {
8944                                Log.e(TAG, "Failed to copy profile " +
8945                                        profileFile.getAbsolutePath() + " ", e);
8946                            }
8947                        }
8948                    }
8949                }
8950            }
8951
8952            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8953                if (DEBUG_DEXOPT) {
8954                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8955                }
8956                numberOfPackagesSkipped++;
8957                continue;
8958            }
8959
8960            if (DEBUG_DEXOPT) {
8961                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8962                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8963            }
8964
8965            if (showDialog) {
8966                try {
8967                    ActivityManager.getService().showBootMessage(
8968                            mContext.getResources().getString(R.string.android_upgrading_apk,
8969                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8970                } catch (RemoteException e) {
8971                }
8972                synchronized (mPackages) {
8973                    mDexOptDialogShown = true;
8974                }
8975            }
8976
8977            String pkgCompilerFilter = compilerFilter;
8978            if (useProfileForDexopt) {
8979                // Use background dexopt mode to try and use the profile. Note that this does not
8980                // guarantee usage of the profile.
8981                pkgCompilerFilter =
8982                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
8983                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
8984            }
8985
8986            // checkProfiles is false to avoid merging profiles during boot which
8987            // might interfere with background compilation (b/28612421).
8988            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8989            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8990            // trade-off worth doing to save boot time work.
8991            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8992            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8993                    pkg.packageName,
8994                    pkgCompilerFilter,
8995                    dexoptFlags));
8996
8997            switch (primaryDexOptStaus) {
8998                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8999                    numberOfPackagesOptimized++;
9000                    break;
9001                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9002                    numberOfPackagesSkipped++;
9003                    break;
9004                case PackageDexOptimizer.DEX_OPT_FAILED:
9005                    numberOfPackagesFailed++;
9006                    break;
9007                default:
9008                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9009                    break;
9010            }
9011        }
9012
9013        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9014                numberOfPackagesFailed };
9015    }
9016
9017    @Override
9018    public void notifyPackageUse(String packageName, int reason) {
9019        synchronized (mPackages) {
9020            final int callingUid = Binder.getCallingUid();
9021            final int callingUserId = UserHandle.getUserId(callingUid);
9022            if (getInstantAppPackageName(callingUid) != null) {
9023                if (!isCallerSameApp(packageName, callingUid)) {
9024                    return;
9025                }
9026            } else {
9027                if (isInstantApp(packageName, callingUserId)) {
9028                    return;
9029                }
9030            }
9031            notifyPackageUseLocked(packageName, reason);
9032        }
9033    }
9034
9035    @GuardedBy("mPackages")
9036    private void notifyPackageUseLocked(String packageName, int reason) {
9037        final PackageParser.Package p = mPackages.get(packageName);
9038        if (p == null) {
9039            return;
9040        }
9041        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9042    }
9043
9044    @Override
9045    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9046            List<String> classPaths, String loaderIsa) {
9047        int userId = UserHandle.getCallingUserId();
9048        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9049        if (ai == null) {
9050            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9051                + loadingPackageName + ", user=" + userId);
9052            return;
9053        }
9054        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9055    }
9056
9057    @Override
9058    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9059            IDexModuleRegisterCallback callback) {
9060        int userId = UserHandle.getCallingUserId();
9061        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9062        DexManager.RegisterDexModuleResult result;
9063        if (ai == null) {
9064            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9065                     " calling user. package=" + packageName + ", user=" + userId);
9066            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9067        } else {
9068            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9069        }
9070
9071        if (callback != null) {
9072            mHandler.post(() -> {
9073                try {
9074                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9075                } catch (RemoteException e) {
9076                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9077                }
9078            });
9079        }
9080    }
9081
9082    /**
9083     * Ask the package manager to perform a dex-opt with the given compiler filter.
9084     *
9085     * Note: exposed only for the shell command to allow moving packages explicitly to a
9086     *       definite state.
9087     */
9088    @Override
9089    public boolean performDexOptMode(String packageName,
9090            boolean checkProfiles, String targetCompilerFilter, boolean force,
9091            boolean bootComplete, String splitName) {
9092        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9093                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9094                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9095        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9096                splitName, flags));
9097    }
9098
9099    /**
9100     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9101     * secondary dex files belonging to the given package.
9102     *
9103     * Note: exposed only for the shell command to allow moving packages explicitly to a
9104     *       definite state.
9105     */
9106    @Override
9107    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9108            boolean force) {
9109        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9110                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9111                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9112                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9113        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9114    }
9115
9116    /*package*/ boolean performDexOpt(DexoptOptions options) {
9117        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9118            return false;
9119        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9120            return false;
9121        }
9122
9123        if (options.isDexoptOnlySecondaryDex()) {
9124            return mDexManager.dexoptSecondaryDex(options);
9125        } else {
9126            int dexoptStatus = performDexOptWithStatus(options);
9127            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9128        }
9129    }
9130
9131    /**
9132     * Perform dexopt on the given package and return one of following result:
9133     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9134     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9135     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9136     */
9137    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9138        return performDexOptTraced(options);
9139    }
9140
9141    private int performDexOptTraced(DexoptOptions options) {
9142        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9143        try {
9144            return performDexOptInternal(options);
9145        } finally {
9146            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9147        }
9148    }
9149
9150    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9151    // if the package can now be considered up to date for the given filter.
9152    private int performDexOptInternal(DexoptOptions options) {
9153        PackageParser.Package p;
9154        synchronized (mPackages) {
9155            p = mPackages.get(options.getPackageName());
9156            if (p == null) {
9157                // Package could not be found. Report failure.
9158                return PackageDexOptimizer.DEX_OPT_FAILED;
9159            }
9160            mPackageUsage.maybeWriteAsync(mPackages);
9161            mCompilerStats.maybeWriteAsync();
9162        }
9163        long callingId = Binder.clearCallingIdentity();
9164        try {
9165            synchronized (mInstallLock) {
9166                return performDexOptInternalWithDependenciesLI(p, options);
9167            }
9168        } finally {
9169            Binder.restoreCallingIdentity(callingId);
9170        }
9171    }
9172
9173    public ArraySet<String> getOptimizablePackages() {
9174        ArraySet<String> pkgs = new ArraySet<String>();
9175        synchronized (mPackages) {
9176            for (PackageParser.Package p : mPackages.values()) {
9177                if (PackageDexOptimizer.canOptimizePackage(p)) {
9178                    pkgs.add(p.packageName);
9179                }
9180            }
9181        }
9182        return pkgs;
9183    }
9184
9185    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9186            DexoptOptions options) {
9187        // Select the dex optimizer based on the force parameter.
9188        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9189        //       allocate an object here.
9190        PackageDexOptimizer pdo = options.isForce()
9191                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9192                : mPackageDexOptimizer;
9193
9194        // Dexopt all dependencies first. Note: we ignore the return value and march on
9195        // on errors.
9196        // Note that we are going to call performDexOpt on those libraries as many times as
9197        // they are referenced in packages. When we do a batch of performDexOpt (for example
9198        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9199        // and the first package that uses the library will dexopt it. The
9200        // others will see that the compiled code for the library is up to date.
9201        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9202        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9203        if (!deps.isEmpty()) {
9204            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9205                    options.getCompilerFilter(), options.getSplitName(),
9206                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9207            for (PackageParser.Package depPackage : deps) {
9208                // TODO: Analyze and investigate if we (should) profile libraries.
9209                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9210                        getOrCreateCompilerPackageStats(depPackage),
9211                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9212            }
9213        }
9214        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9215                getOrCreateCompilerPackageStats(p),
9216                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9217    }
9218
9219    /**
9220     * Reconcile the information we have about the secondary dex files belonging to
9221     * {@code packagName} and the actual dex files. For all dex files that were
9222     * deleted, update the internal records and delete the generated oat files.
9223     */
9224    @Override
9225    public void reconcileSecondaryDexFiles(String packageName) {
9226        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9227            return;
9228        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9229            return;
9230        }
9231        mDexManager.reconcileSecondaryDexFiles(packageName);
9232    }
9233
9234    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9235    // a reference there.
9236    /*package*/ DexManager getDexManager() {
9237        return mDexManager;
9238    }
9239
9240    /**
9241     * Execute the background dexopt job immediately.
9242     */
9243    @Override
9244    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9245        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9246            return false;
9247        }
9248        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9249    }
9250
9251    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9252        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9253                || p.usesStaticLibraries != null) {
9254            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9255            Set<String> collectedNames = new HashSet<>();
9256            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9257
9258            retValue.remove(p);
9259
9260            return retValue;
9261        } else {
9262            return Collections.emptyList();
9263        }
9264    }
9265
9266    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9267            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9268        if (!collectedNames.contains(p.packageName)) {
9269            collectedNames.add(p.packageName);
9270            collected.add(p);
9271
9272            if (p.usesLibraries != null) {
9273                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9274                        null, collected, collectedNames);
9275            }
9276            if (p.usesOptionalLibraries != null) {
9277                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9278                        null, collected, collectedNames);
9279            }
9280            if (p.usesStaticLibraries != null) {
9281                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9282                        p.usesStaticLibrariesVersions, collected, collectedNames);
9283            }
9284        }
9285    }
9286
9287    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9288            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9289        final int libNameCount = libs.size();
9290        for (int i = 0; i < libNameCount; i++) {
9291            String libName = libs.get(i);
9292            long version = (versions != null && versions.length == libNameCount)
9293                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9294            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9295            if (libPkg != null) {
9296                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9297            }
9298        }
9299    }
9300
9301    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9302        synchronized (mPackages) {
9303            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9304            if (libEntry != null) {
9305                return mPackages.get(libEntry.apk);
9306            }
9307            return null;
9308        }
9309    }
9310
9311    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9312        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9313        if (versionedLib == null) {
9314            return null;
9315        }
9316        return versionedLib.get(version);
9317    }
9318
9319    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9320        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9321                pkg.staticSharedLibName);
9322        if (versionedLib == null) {
9323            return null;
9324        }
9325        long previousLibVersion = -1;
9326        final int versionCount = versionedLib.size();
9327        for (int i = 0; i < versionCount; i++) {
9328            final long libVersion = versionedLib.keyAt(i);
9329            if (libVersion < pkg.staticSharedLibVersion) {
9330                previousLibVersion = Math.max(previousLibVersion, libVersion);
9331            }
9332        }
9333        if (previousLibVersion >= 0) {
9334            return versionedLib.get(previousLibVersion);
9335        }
9336        return null;
9337    }
9338
9339    public void shutdown() {
9340        mPackageUsage.writeNow(mPackages);
9341        mCompilerStats.writeNow();
9342        mDexManager.writePackageDexUsageNow();
9343    }
9344
9345    @Override
9346    public void dumpProfiles(String packageName) {
9347        PackageParser.Package pkg;
9348        synchronized (mPackages) {
9349            pkg = mPackages.get(packageName);
9350            if (pkg == null) {
9351                throw new IllegalArgumentException("Unknown package: " + packageName);
9352            }
9353        }
9354        /* Only the shell, root, or the app user should be able to dump profiles. */
9355        int callingUid = Binder.getCallingUid();
9356        if (callingUid != Process.SHELL_UID &&
9357            callingUid != Process.ROOT_UID &&
9358            callingUid != pkg.applicationInfo.uid) {
9359            throw new SecurityException("dumpProfiles");
9360        }
9361
9362        synchronized (mInstallLock) {
9363            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9364            mArtManagerService.dumpProfiles(pkg);
9365            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9366        }
9367    }
9368
9369    @Override
9370    public void forceDexOpt(String packageName) {
9371        enforceSystemOrRoot("forceDexOpt");
9372
9373        PackageParser.Package pkg;
9374        synchronized (mPackages) {
9375            pkg = mPackages.get(packageName);
9376            if (pkg == null) {
9377                throw new IllegalArgumentException("Unknown package: " + packageName);
9378            }
9379        }
9380
9381        synchronized (mInstallLock) {
9382            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9383
9384            // Whoever is calling forceDexOpt wants a compiled package.
9385            // Don't use profiles since that may cause compilation to be skipped.
9386            final int res = performDexOptInternalWithDependenciesLI(
9387                    pkg,
9388                    new DexoptOptions(packageName,
9389                            getDefaultCompilerFilter(),
9390                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9391
9392            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9393            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9394                throw new IllegalStateException("Failed to dexopt: " + res);
9395            }
9396        }
9397    }
9398
9399    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9400        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9401            Slog.w(TAG, "Unable to update from " + oldPkg.name
9402                    + " to " + newPkg.packageName
9403                    + ": old package not in system partition");
9404            return false;
9405        } else if (mPackages.get(oldPkg.name) != null) {
9406            Slog.w(TAG, "Unable to update from " + oldPkg.name
9407                    + " to " + newPkg.packageName
9408                    + ": old package still exists");
9409            return false;
9410        }
9411        return true;
9412    }
9413
9414    void removeCodePathLI(File codePath) {
9415        if (codePath.isDirectory()) {
9416            try {
9417                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9418            } catch (InstallerException e) {
9419                Slog.w(TAG, "Failed to remove code path", e);
9420            }
9421        } else {
9422            codePath.delete();
9423        }
9424    }
9425
9426    private int[] resolveUserIds(int userId) {
9427        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9428    }
9429
9430    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9431        if (pkg == null) {
9432            Slog.wtf(TAG, "Package was null!", new Throwable());
9433            return;
9434        }
9435        clearAppDataLeafLIF(pkg, userId, flags);
9436        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9437        for (int i = 0; i < childCount; i++) {
9438            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9439        }
9440
9441        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9442    }
9443
9444    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9445        final PackageSetting ps;
9446        synchronized (mPackages) {
9447            ps = mSettings.mPackages.get(pkg.packageName);
9448        }
9449        for (int realUserId : resolveUserIds(userId)) {
9450            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9451            try {
9452                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9453                        ceDataInode);
9454            } catch (InstallerException e) {
9455                Slog.w(TAG, String.valueOf(e));
9456            }
9457        }
9458    }
9459
9460    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9461        if (pkg == null) {
9462            Slog.wtf(TAG, "Package was null!", new Throwable());
9463            return;
9464        }
9465        destroyAppDataLeafLIF(pkg, userId, flags);
9466        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9467        for (int i = 0; i < childCount; i++) {
9468            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9469        }
9470    }
9471
9472    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9473        final PackageSetting ps;
9474        synchronized (mPackages) {
9475            ps = mSettings.mPackages.get(pkg.packageName);
9476        }
9477        for (int realUserId : resolveUserIds(userId)) {
9478            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9479            try {
9480                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9481                        ceDataInode);
9482            } catch (InstallerException e) {
9483                Slog.w(TAG, String.valueOf(e));
9484            }
9485            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9486        }
9487    }
9488
9489    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9490        if (pkg == null) {
9491            Slog.wtf(TAG, "Package was null!", new Throwable());
9492            return;
9493        }
9494        destroyAppProfilesLeafLIF(pkg);
9495        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9496        for (int i = 0; i < childCount; i++) {
9497            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9498        }
9499    }
9500
9501    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9502        try {
9503            mInstaller.destroyAppProfiles(pkg.packageName);
9504        } catch (InstallerException e) {
9505            Slog.w(TAG, String.valueOf(e));
9506        }
9507    }
9508
9509    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9510        if (pkg == null) {
9511            Slog.wtf(TAG, "Package was null!", new Throwable());
9512            return;
9513        }
9514        mArtManagerService.clearAppProfiles(pkg);
9515        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9516        for (int i = 0; i < childCount; i++) {
9517            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9518        }
9519    }
9520
9521    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9522            long lastUpdateTime) {
9523        // Set parent install/update time
9524        PackageSetting ps = (PackageSetting) pkg.mExtras;
9525        if (ps != null) {
9526            ps.firstInstallTime = firstInstallTime;
9527            ps.lastUpdateTime = lastUpdateTime;
9528        }
9529        // Set children install/update time
9530        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9531        for (int i = 0; i < childCount; i++) {
9532            PackageParser.Package childPkg = pkg.childPackages.get(i);
9533            ps = (PackageSetting) childPkg.mExtras;
9534            if (ps != null) {
9535                ps.firstInstallTime = firstInstallTime;
9536                ps.lastUpdateTime = lastUpdateTime;
9537            }
9538        }
9539    }
9540
9541    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9542            SharedLibraryEntry file,
9543            PackageParser.Package changingLib) {
9544        if (file.path != null) {
9545            usesLibraryFiles.add(file.path);
9546            return;
9547        }
9548        PackageParser.Package p = mPackages.get(file.apk);
9549        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9550            // If we are doing this while in the middle of updating a library apk,
9551            // then we need to make sure to use that new apk for determining the
9552            // dependencies here.  (We haven't yet finished committing the new apk
9553            // to the package manager state.)
9554            if (p == null || p.packageName.equals(changingLib.packageName)) {
9555                p = changingLib;
9556            }
9557        }
9558        if (p != null) {
9559            usesLibraryFiles.addAll(p.getAllCodePaths());
9560            if (p.usesLibraryFiles != null) {
9561                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9562            }
9563        }
9564    }
9565
9566    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9567            PackageParser.Package changingLib) throws PackageManagerException {
9568        if (pkg == null) {
9569            return;
9570        }
9571        // The collection used here must maintain the order of addition (so
9572        // that libraries are searched in the correct order) and must have no
9573        // duplicates.
9574        Set<String> usesLibraryFiles = null;
9575        if (pkg.usesLibraries != null) {
9576            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9577                    null, null, pkg.packageName, changingLib, true,
9578                    pkg.applicationInfo.targetSdkVersion, null);
9579        }
9580        if (pkg.usesStaticLibraries != null) {
9581            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9582                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9583                    pkg.packageName, changingLib, true,
9584                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9585        }
9586        if (pkg.usesOptionalLibraries != null) {
9587            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9588                    null, null, pkg.packageName, changingLib, false,
9589                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9590        }
9591        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9592            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9593        } else {
9594            pkg.usesLibraryFiles = null;
9595        }
9596    }
9597
9598    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9599            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9600            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9601            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9602            throws PackageManagerException {
9603        final int libCount = requestedLibraries.size();
9604        for (int i = 0; i < libCount; i++) {
9605            final String libName = requestedLibraries.get(i);
9606            final long libVersion = requiredVersions != null ? requiredVersions[i]
9607                    : SharedLibraryInfo.VERSION_UNDEFINED;
9608            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9609            if (libEntry == null) {
9610                if (required) {
9611                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9612                            "Package " + packageName + " requires unavailable shared library "
9613                                    + libName + "; failing!");
9614                } else if (DEBUG_SHARED_LIBRARIES) {
9615                    Slog.i(TAG, "Package " + packageName
9616                            + " desires unavailable shared library "
9617                            + libName + "; ignoring!");
9618                }
9619            } else {
9620                if (requiredVersions != null && requiredCertDigests != null) {
9621                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9622                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9623                            "Package " + packageName + " requires unavailable static shared"
9624                                    + " library " + libName + " version "
9625                                    + libEntry.info.getLongVersion() + "; failing!");
9626                    }
9627
9628                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9629                    if (libPkg == null) {
9630                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9631                                "Package " + packageName + " requires unavailable static shared"
9632                                        + " library; failing!");
9633                    }
9634
9635                    final String[] expectedCertDigests = requiredCertDigests[i];
9636
9637
9638                    if (expectedCertDigests.length > 1) {
9639
9640                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9641                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9642                                ? PackageUtils.computeSignaturesSha256Digests(
9643                                libPkg.mSigningDetails.signatures)
9644                                : PackageUtils.computeSignaturesSha256Digests(
9645                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9646
9647                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9648                        // target O we don't parse the "additional-certificate" tags similarly
9649                        // how we only consider all certs only for apps targeting O (see above).
9650                        // Therefore, the size check is safe to make.
9651                        if (expectedCertDigests.length != libCertDigests.length) {
9652                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9653                                    "Package " + packageName + " requires differently signed" +
9654                                            " static shared library; failing!");
9655                        }
9656
9657                        // Use a predictable order as signature order may vary
9658                        Arrays.sort(libCertDigests);
9659                        Arrays.sort(expectedCertDigests);
9660
9661                        final int certCount = libCertDigests.length;
9662                        for (int j = 0; j < certCount; j++) {
9663                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9664                                throw new PackageManagerException(
9665                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9666                                        "Package " + packageName + " requires differently signed" +
9667                                                " static shared library; failing!");
9668                            }
9669                        }
9670                    } else {
9671
9672                        // lib signing cert could have rotated beyond the one expected, check to see
9673                        // if the new one has been blessed by the old
9674                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9675                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9676                            throw new PackageManagerException(
9677                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9678                                    "Package " + packageName + " requires differently signed" +
9679                                            " static shared library; failing!");
9680                        }
9681                    }
9682                }
9683
9684                if (outUsedLibraries == null) {
9685                    // Use LinkedHashSet to preserve the order of files added to
9686                    // usesLibraryFiles while eliminating duplicates.
9687                    outUsedLibraries = new LinkedHashSet<>();
9688                }
9689                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9690            }
9691        }
9692        return outUsedLibraries;
9693    }
9694
9695    private static boolean hasString(List<String> list, List<String> which) {
9696        if (list == null) {
9697            return false;
9698        }
9699        for (int i=list.size()-1; i>=0; i--) {
9700            for (int j=which.size()-1; j>=0; j--) {
9701                if (which.get(j).equals(list.get(i))) {
9702                    return true;
9703                }
9704            }
9705        }
9706        return false;
9707    }
9708
9709    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9710            PackageParser.Package changingPkg) {
9711        ArrayList<PackageParser.Package> res = null;
9712        for (PackageParser.Package pkg : mPackages.values()) {
9713            if (changingPkg != null
9714                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9715                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9716                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9717                            changingPkg.staticSharedLibName)) {
9718                return null;
9719            }
9720            if (res == null) {
9721                res = new ArrayList<>();
9722            }
9723            res.add(pkg);
9724            try {
9725                updateSharedLibrariesLPr(pkg, changingPkg);
9726            } catch (PackageManagerException e) {
9727                // If a system app update or an app and a required lib missing we
9728                // delete the package and for updated system apps keep the data as
9729                // it is better for the user to reinstall than to be in an limbo
9730                // state. Also libs disappearing under an app should never happen
9731                // - just in case.
9732                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9733                    final int flags = pkg.isUpdatedSystemApp()
9734                            ? PackageManager.DELETE_KEEP_DATA : 0;
9735                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9736                            flags , null, true, null);
9737                }
9738                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9739            }
9740        }
9741        return res;
9742    }
9743
9744    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9745            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9746            @Nullable UserHandle user) throws PackageManagerException {
9747        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9748        // If the package has children and this is the first dive in the function
9749        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9750        // whether all packages (parent and children) would be successfully scanned
9751        // before the actual scan since scanning mutates internal state and we want
9752        // to atomically install the package and its children.
9753        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9754            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9755                scanFlags |= SCAN_CHECK_ONLY;
9756            }
9757        } else {
9758            scanFlags &= ~SCAN_CHECK_ONLY;
9759        }
9760
9761        final PackageParser.Package scannedPkg;
9762        try {
9763            // Scan the parent
9764            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9765            // Scan the children
9766            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9767            for (int i = 0; i < childCount; i++) {
9768                PackageParser.Package childPkg = pkg.childPackages.get(i);
9769                scanPackageNewLI(childPkg, parseFlags,
9770                        scanFlags, currentTime, user);
9771            }
9772        } finally {
9773            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9774        }
9775
9776        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9777            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9778        }
9779
9780        return scannedPkg;
9781    }
9782
9783    /** The result of a package scan. */
9784    private static class ScanResult {
9785        /** Whether or not the package scan was successful */
9786        public final boolean success;
9787        /**
9788         * The final package settings. This may be the same object passed in
9789         * the {@link ScanRequest}, but, with modified values.
9790         */
9791        @Nullable public final PackageSetting pkgSetting;
9792        /** ABI code paths that have changed in the package scan */
9793        @Nullable public final List<String> changedAbiCodePath;
9794        public ScanResult(
9795                boolean success,
9796                @Nullable PackageSetting pkgSetting,
9797                @Nullable List<String> changedAbiCodePath) {
9798            this.success = success;
9799            this.pkgSetting = pkgSetting;
9800            this.changedAbiCodePath = changedAbiCodePath;
9801        }
9802    }
9803
9804    /** A package to be scanned */
9805    private static class ScanRequest {
9806        /** The parsed package */
9807        @NonNull public final PackageParser.Package pkg;
9808        /** Shared user settings, if the package has a shared user */
9809        @Nullable public final SharedUserSetting sharedUserSetting;
9810        /**
9811         * Package settings of the currently installed version.
9812         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9813         * during scan.
9814         */
9815        @Nullable public final PackageSetting pkgSetting;
9816        /** A copy of the settings for the currently installed version */
9817        @Nullable public final PackageSetting oldPkgSetting;
9818        /** Package settings for the disabled version on the /system partition */
9819        @Nullable public final PackageSetting disabledPkgSetting;
9820        /** Package settings for the installed version under its original package name */
9821        @Nullable public final PackageSetting originalPkgSetting;
9822        /** The real package name of a renamed application */
9823        @Nullable public final String realPkgName;
9824        public final @ParseFlags int parseFlags;
9825        public final @ScanFlags int scanFlags;
9826        /** The user for which the package is being scanned */
9827        @Nullable public final UserHandle user;
9828        /** Whether or not the platform package is being scanned */
9829        public final boolean isPlatformPackage;
9830        public ScanRequest(
9831                @NonNull PackageParser.Package pkg,
9832                @Nullable SharedUserSetting sharedUserSetting,
9833                @Nullable PackageSetting pkgSetting,
9834                @Nullable PackageSetting disabledPkgSetting,
9835                @Nullable PackageSetting originalPkgSetting,
9836                @Nullable String realPkgName,
9837                @ParseFlags int parseFlags,
9838                @ScanFlags int scanFlags,
9839                boolean isPlatformPackage,
9840                @Nullable UserHandle user) {
9841            this.pkg = pkg;
9842            this.pkgSetting = pkgSetting;
9843            this.sharedUserSetting = sharedUserSetting;
9844            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9845            this.disabledPkgSetting = disabledPkgSetting;
9846            this.originalPkgSetting = originalPkgSetting;
9847            this.realPkgName = realPkgName;
9848            this.parseFlags = parseFlags;
9849            this.scanFlags = scanFlags;
9850            this.isPlatformPackage = isPlatformPackage;
9851            this.user = user;
9852        }
9853    }
9854
9855    /**
9856     * Returns the actual scan flags depending upon the state of the other settings.
9857     * <p>Updated system applications will not have the following flags set
9858     * by default and need to be adjusted after the fact:
9859     * <ul>
9860     * <li>{@link #SCAN_AS_SYSTEM}</li>
9861     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9862     * <li>{@link #SCAN_AS_OEM}</li>
9863     * <li>{@link #SCAN_AS_VENDOR}</li>
9864     * <li>{@link #SCAN_AS_PRODUCT}</li>
9865     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9866     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9867     * </ul>
9868     */
9869    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9870            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9871            PackageParser.Package pkg) {
9872        if (disabledPkgSetting != null) {
9873            // updated system application, must at least have SCAN_AS_SYSTEM
9874            scanFlags |= SCAN_AS_SYSTEM;
9875            if ((disabledPkgSetting.pkgPrivateFlags
9876                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9877                scanFlags |= SCAN_AS_PRIVILEGED;
9878            }
9879            if ((disabledPkgSetting.pkgPrivateFlags
9880                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9881                scanFlags |= SCAN_AS_OEM;
9882            }
9883            if ((disabledPkgSetting.pkgPrivateFlags
9884                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9885                scanFlags |= SCAN_AS_VENDOR;
9886            }
9887            if ((disabledPkgSetting.pkgPrivateFlags
9888                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9889                scanFlags |= SCAN_AS_PRODUCT;
9890            }
9891        }
9892        if (pkgSetting != null) {
9893            final int userId = ((user == null) ? 0 : user.getIdentifier());
9894            if (pkgSetting.getInstantApp(userId)) {
9895                scanFlags |= SCAN_AS_INSTANT_APP;
9896            }
9897            if (pkgSetting.getVirtulalPreload(userId)) {
9898                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9899            }
9900        }
9901
9902        // Scan as privileged apps that share a user with a priv-app.
9903        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9904                && (pkg.mSharedUserId != null)) {
9905            SharedUserSetting sharedUserSetting = null;
9906            try {
9907                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9908            } catch (PackageManagerException ignore) {}
9909            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9910                // Exempt SharedUsers signed with the platform key.
9911                // TODO(b/72378145) Fix this exemption. Force signature apps
9912                // to whitelist their privileged permissions just like other
9913                // priv-apps.
9914                synchronized (mPackages) {
9915                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9916                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9917                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9918                        scanFlags |= SCAN_AS_PRIVILEGED;
9919                    }
9920                }
9921            }
9922        }
9923
9924        return scanFlags;
9925    }
9926
9927    @GuardedBy("mInstallLock")
9928    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9929            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9930            @Nullable UserHandle user) throws PackageManagerException {
9931
9932        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9933        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9934        if (realPkgName != null) {
9935            ensurePackageRenamed(pkg, renamedPkgName);
9936        }
9937        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9938        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9939        final PackageSetting disabledPkgSetting =
9940                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9941
9942        if (mTransferedPackages.contains(pkg.packageName)) {
9943            Slog.w(TAG, "Package " + pkg.packageName
9944                    + " was transferred to another, but its .apk remains");
9945        }
9946
9947        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
9948        synchronized (mPackages) {
9949            applyPolicy(pkg, parseFlags, scanFlags);
9950            assertPackageIsValid(pkg, parseFlags, scanFlags);
9951
9952            SharedUserSetting sharedUserSetting = null;
9953            if (pkg.mSharedUserId != null) {
9954                // SIDE EFFECTS; may potentially allocate a new shared user
9955                sharedUserSetting = mSettings.getSharedUserLPw(
9956                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9957                if (DEBUG_PACKAGE_SCANNING) {
9958                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9959                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
9960                                + " (uid=" + sharedUserSetting.userId + "):"
9961                                + " packages=" + sharedUserSetting.packages);
9962                }
9963            }
9964
9965            boolean scanSucceeded = false;
9966            try {
9967                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
9968                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
9969                        (pkg == mPlatformPackage), user);
9970                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
9971                if (result.success) {
9972                    commitScanResultsLocked(request, result);
9973                }
9974                scanSucceeded = true;
9975            } finally {
9976                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9977                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
9978                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9979                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9980                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9981                  }
9982            }
9983        }
9984        return pkg;
9985    }
9986
9987    /**
9988     * Commits the package scan and modifies system state.
9989     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
9990     * of committing the package, leaving the system in an inconsistent state.
9991     * This needs to be fixed so, once we get to this point, no errors are
9992     * possible and the system is not left in an inconsistent state.
9993     */
9994    @GuardedBy("mPackages")
9995    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
9996            throws PackageManagerException {
9997        final PackageParser.Package pkg = request.pkg;
9998        final @ParseFlags int parseFlags = request.parseFlags;
9999        final @ScanFlags int scanFlags = request.scanFlags;
10000        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10001        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10002        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10003        final UserHandle user = request.user;
10004        final String realPkgName = request.realPkgName;
10005        final PackageSetting pkgSetting = result.pkgSetting;
10006        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10007        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10008
10009        if (newPkgSettingCreated) {
10010            if (originalPkgSetting != null) {
10011                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10012            }
10013            // THROWS: when we can't allocate a user id. add call to check if there's
10014            // enough space to ensure we won't throw; otherwise, don't modify state
10015            mSettings.addUserToSettingLPw(pkgSetting);
10016
10017            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10018                mTransferedPackages.add(originalPkgSetting.name);
10019            }
10020        }
10021        // TODO(toddke): Consider a method specifically for modifying the Package object
10022        // post scan; or, moving this stuff out of the Package object since it has nothing
10023        // to do with the package on disk.
10024        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10025        // for creating the application ID. If we did this earlier, we would be saving the
10026        // correct ID.
10027        pkg.applicationInfo.uid = pkgSetting.appId;
10028
10029        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10030
10031        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10032            mTransferedPackages.add(pkg.packageName);
10033        }
10034
10035        // THROWS: when requested libraries that can't be found. it only changes
10036        // the state of the passed in pkg object, so, move to the top of the method
10037        // and allow it to abort
10038        if ((scanFlags & SCAN_BOOTING) == 0
10039                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10040            // Check all shared libraries and map to their actual file path.
10041            // We only do this here for apps not on a system dir, because those
10042            // are the only ones that can fail an install due to this.  We
10043            // will take care of the system apps by updating all of their
10044            // library paths after the scan is done. Also during the initial
10045            // scan don't update any libs as we do this wholesale after all
10046            // apps are scanned to avoid dependency based scanning.
10047            updateSharedLibrariesLPr(pkg, null);
10048        }
10049
10050        // All versions of a static shared library are referenced with the same
10051        // package name. Internally, we use a synthetic package name to allow
10052        // multiple versions of the same shared library to be installed. So,
10053        // we need to generate the synthetic package name of the latest shared
10054        // library in order to compare signatures.
10055        PackageSetting signatureCheckPs = pkgSetting;
10056        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10057            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10058            if (libraryEntry != null) {
10059                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10060            }
10061        }
10062
10063        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10064        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10065            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10066                // We just determined the app is signed correctly, so bring
10067                // over the latest parsed certs.
10068                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10069            } else {
10070                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10071                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10072                            "Package " + pkg.packageName + " upgrade keys do not match the "
10073                                    + "previously installed version");
10074                } else {
10075                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10076                    String msg = "System package " + pkg.packageName
10077                            + " signature changed; retaining data.";
10078                    reportSettingsProblem(Log.WARN, msg);
10079                }
10080            }
10081        } else {
10082            try {
10083                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10084                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10085                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10086                        pkg.mSigningDetails, compareCompat, compareRecover);
10087                // The new KeySets will be re-added later in the scanning process.
10088                if (compatMatch) {
10089                    synchronized (mPackages) {
10090                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10091                    }
10092                }
10093                // We just determined the app is signed correctly, so bring
10094                // over the latest parsed certs.
10095                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10096
10097
10098                // if this is is a sharedUser, check to see if the new package is signed by a newer
10099                // signing certificate than the existing one, and if so, copy over the new details
10100                if (signatureCheckPs.sharedUser != null
10101                        && pkg.mSigningDetails.hasAncestor(
10102                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10103                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10104                }
10105            } catch (PackageManagerException e) {
10106                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10107                    throw e;
10108                }
10109                // The signature has changed, but this package is in the system
10110                // image...  let's recover!
10111                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10112                // However...  if this package is part of a shared user, but it
10113                // doesn't match the signature of the shared user, let's fail.
10114                // What this means is that you can't change the signatures
10115                // associated with an overall shared user, which doesn't seem all
10116                // that unreasonable.
10117                if (signatureCheckPs.sharedUser != null) {
10118                    if (compareSignatures(
10119                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10120                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10121                        throw new PackageManagerException(
10122                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10123                                "Signature mismatch for shared user: "
10124                                        + pkgSetting.sharedUser);
10125                    }
10126                }
10127                // File a report about this.
10128                String msg = "System package " + pkg.packageName
10129                        + " signature changed; retaining data.";
10130                reportSettingsProblem(Log.WARN, msg);
10131            } catch (IllegalArgumentException e) {
10132
10133                // should never happen: certs matched when checking, but not when comparing
10134                // old to new for sharedUser
10135                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10136                        "Signing certificates comparison made on incomparable signing details"
10137                        + " but somehow passed verifySignatures!");
10138            }
10139        }
10140
10141        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10142            // This package wants to adopt ownership of permissions from
10143            // another package.
10144            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10145                final String origName = pkg.mAdoptPermissions.get(i);
10146                final PackageSetting orig = mSettings.getPackageLPr(origName);
10147                if (orig != null) {
10148                    if (verifyPackageUpdateLPr(orig, pkg)) {
10149                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10150                                + pkg.packageName);
10151                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10152                    }
10153                }
10154            }
10155        }
10156
10157        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10158            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10159                final String codePathString = changedAbiCodePath.get(i);
10160                try {
10161                    mInstaller.rmdex(codePathString,
10162                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10163                } catch (InstallerException ignored) {
10164                }
10165            }
10166        }
10167
10168        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10169            if (oldPkgSetting != null) {
10170                synchronized (mPackages) {
10171                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10172                }
10173            }
10174        } else {
10175            final int userId = user == null ? 0 : user.getIdentifier();
10176            // Modify state for the given package setting
10177            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10178                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10179            if (pkgSetting.getInstantApp(userId)) {
10180                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10181            }
10182        }
10183    }
10184
10185    /**
10186     * Returns the "real" name of the package.
10187     * <p>This may differ from the package's actual name if the application has already
10188     * been installed under one of this package's original names.
10189     */
10190    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10191            @Nullable String renamedPkgName) {
10192        if (isPackageRenamed(pkg, renamedPkgName)) {
10193            return pkg.mRealPackage;
10194        }
10195        return null;
10196    }
10197
10198    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10199    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10200            @Nullable String renamedPkgName) {
10201        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10202    }
10203
10204    /**
10205     * Returns the original package setting.
10206     * <p>A package can migrate its name during an update. In this scenario, a package
10207     * designates a set of names that it considers as one of its original names.
10208     * <p>An original package must be signed identically and it must have the same
10209     * shared user [if any].
10210     */
10211    @GuardedBy("mPackages")
10212    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10213            @Nullable String renamedPkgName) {
10214        if (!isPackageRenamed(pkg, renamedPkgName)) {
10215            return null;
10216        }
10217        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10218            final PackageSetting originalPs =
10219                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10220            if (originalPs != null) {
10221                // the package is already installed under its original name...
10222                // but, should we use it?
10223                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10224                    // the new package is incompatible with the original
10225                    continue;
10226                } else if (originalPs.sharedUser != null) {
10227                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10228                        // the shared user id is incompatible with the original
10229                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10230                                + " to " + pkg.packageName + ": old uid "
10231                                + originalPs.sharedUser.name
10232                                + " differs from " + pkg.mSharedUserId);
10233                        continue;
10234                    }
10235                    // TODO: Add case when shared user id is added [b/28144775]
10236                } else {
10237                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10238                            + pkg.packageName + " to old name " + originalPs.name);
10239                }
10240                return originalPs;
10241            }
10242        }
10243        return null;
10244    }
10245
10246    /**
10247     * Renames the package if it was installed under a different name.
10248     * <p>When we've already installed the package under an original name, update
10249     * the new package so we can continue to have the old name.
10250     */
10251    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10252            @NonNull String renamedPackageName) {
10253        if (pkg.mOriginalPackages == null
10254                || !pkg.mOriginalPackages.contains(renamedPackageName)
10255                || pkg.packageName.equals(renamedPackageName)) {
10256            return;
10257        }
10258        pkg.setPackageName(renamedPackageName);
10259    }
10260
10261    /**
10262     * Just scans the package without any side effects.
10263     * <p>Not entirely true at the moment. There is still one side effect -- this
10264     * method potentially modifies a live {@link PackageSetting} object representing
10265     * the package being scanned. This will be resolved in the future.
10266     *
10267     * @param request Information about the package to be scanned
10268     * @param isUnderFactoryTest Whether or not the device is under factory test
10269     * @param currentTime The current time, in millis
10270     * @return The results of the scan
10271     */
10272    @GuardedBy("mInstallLock")
10273    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10274            boolean isUnderFactoryTest, long currentTime)
10275                    throws PackageManagerException {
10276        final PackageParser.Package pkg = request.pkg;
10277        PackageSetting pkgSetting = request.pkgSetting;
10278        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10279        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10280        final @ParseFlags int parseFlags = request.parseFlags;
10281        final @ScanFlags int scanFlags = request.scanFlags;
10282        final String realPkgName = request.realPkgName;
10283        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10284        final UserHandle user = request.user;
10285        final boolean isPlatformPackage = request.isPlatformPackage;
10286
10287        List<String> changedAbiCodePath = null;
10288
10289        if (DEBUG_PACKAGE_SCANNING) {
10290            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10291                Log.d(TAG, "Scanning package " + pkg.packageName);
10292        }
10293
10294        if (Build.IS_DEBUGGABLE &&
10295                pkg.isPrivileged() &&
10296                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10297            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10298        }
10299
10300        // Initialize package source and resource directories
10301        final File scanFile = new File(pkg.codePath);
10302        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10303        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10304
10305        // We keep references to the derived CPU Abis from settings in oder to reuse
10306        // them in the case where we're not upgrading or booting for the first time.
10307        String primaryCpuAbiFromSettings = null;
10308        String secondaryCpuAbiFromSettings = null;
10309        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10310
10311        if (!needToDeriveAbi) {
10312            if (pkgSetting != null) {
10313                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10314                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10315            } else {
10316                // Re-scanning a system package after uninstalling updates; need to derive ABI
10317                needToDeriveAbi = true;
10318            }
10319        }
10320
10321        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10322            PackageManagerService.reportSettingsProblem(Log.WARN,
10323                    "Package " + pkg.packageName + " shared user changed from "
10324                            + (pkgSetting.sharedUser != null
10325                            ? pkgSetting.sharedUser.name : "<nothing>")
10326                            + " to "
10327                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10328                            + "; replacing with new");
10329            pkgSetting = null;
10330        }
10331
10332        String[] usesStaticLibraries = null;
10333        if (pkg.usesStaticLibraries != null) {
10334            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10335            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10336        }
10337        final boolean createNewPackage = (pkgSetting == null);
10338        if (createNewPackage) {
10339            final String parentPackageName = (pkg.parentPackage != null)
10340                    ? pkg.parentPackage.packageName : null;
10341            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10342            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10343            // REMOVE SharedUserSetting from method; update in a separate call
10344            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10345                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10346                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10347                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10348                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10349                    user, true /*allowInstall*/, instantApp, virtualPreload,
10350                    parentPackageName, pkg.getChildPackageNames(),
10351                    UserManagerService.getInstance(), usesStaticLibraries,
10352                    pkg.usesStaticLibrariesVersions);
10353        } else {
10354            // REMOVE SharedUserSetting from method; update in a separate call.
10355            //
10356            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10357            // secondaryCpuAbi are not known at this point so we always update them
10358            // to null here, only to reset them at a later point.
10359            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10360                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10361                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10362                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10363                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10364                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10365        }
10366        if (createNewPackage && originalPkgSetting != null) {
10367            // This is the initial transition from the original package, so,
10368            // fix up the new package's name now. We must do this after looking
10369            // up the package under its new name, so getPackageLP takes care of
10370            // fiddling things correctly.
10371            pkg.setPackageName(originalPkgSetting.name);
10372
10373            // File a report about this.
10374            String msg = "New package " + pkgSetting.realName
10375                    + " renamed to replace old package " + pkgSetting.name;
10376            reportSettingsProblem(Log.WARN, msg);
10377        }
10378
10379        if (disabledPkgSetting != null) {
10380            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10381        }
10382
10383        // SELinux sandboxes become more restrictive as targetSdkVersion increases.
10384        // To ensure that apps with sharedUserId are placed in the same selinux domain
10385        // without breaking any assumptions about access, put them into the least
10386        // restrictive targetSdkVersion=25 domain.
10387        // TODO(b/72290969): Base this on the actual targetSdkVersion(s) of the apps within the
10388        // sharedUserSetting, instead of defaulting to the least restrictive domain.
10389        final int targetSdk = (sharedUserSetting != null) ? 25
10390                : pkg.applicationInfo.targetSdkVersion;
10391        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10392        // They currently can be if the sharedUser apps are signed with the platform key.
10393        final boolean isPrivileged = (sharedUserSetting != null) ?
10394            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10395
10396        SELinuxMMAC.assignSeInfoValue(pkg, isPrivileged, targetSdk);
10397
10398        pkg.mExtras = pkgSetting;
10399        pkg.applicationInfo.processName = fixProcessName(
10400                pkg.applicationInfo.packageName,
10401                pkg.applicationInfo.processName);
10402
10403        if (!isPlatformPackage) {
10404            // Get all of our default paths setup
10405            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10406        }
10407
10408        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10409
10410        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10411            if (needToDeriveAbi) {
10412                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10413                final boolean extractNativeLibs = !pkg.isLibrary();
10414                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10415                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10416
10417                // Some system apps still use directory structure for native libraries
10418                // in which case we might end up not detecting abi solely based on apk
10419                // structure. Try to detect abi based on directory structure.
10420                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10421                        pkg.applicationInfo.primaryCpuAbi == null) {
10422                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10423                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10424                }
10425            } else {
10426                // This is not a first boot or an upgrade, don't bother deriving the
10427                // ABI during the scan. Instead, trust the value that was stored in the
10428                // package setting.
10429                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10430                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10431
10432                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10433
10434                if (DEBUG_ABI_SELECTION) {
10435                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10436                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10437                            pkg.applicationInfo.secondaryCpuAbi);
10438                }
10439            }
10440        } else {
10441            if ((scanFlags & SCAN_MOVE) != 0) {
10442                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10443                // but we already have this packages package info in the PackageSetting. We just
10444                // use that and derive the native library path based on the new codepath.
10445                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10446                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10447            }
10448
10449            // Set native library paths again. For moves, the path will be updated based on the
10450            // ABIs we've determined above. For non-moves, the path will be updated based on the
10451            // ABIs we determined during compilation, but the path will depend on the final
10452            // package path (after the rename away from the stage path).
10453            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10454        }
10455
10456        // This is a special case for the "system" package, where the ABI is
10457        // dictated by the zygote configuration (and init.rc). We should keep track
10458        // of this ABI so that we can deal with "normal" applications that run under
10459        // the same UID correctly.
10460        if (isPlatformPackage) {
10461            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10462                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10463        }
10464
10465        // If there's a mismatch between the abi-override in the package setting
10466        // and the abiOverride specified for the install. Warn about this because we
10467        // would've already compiled the app without taking the package setting into
10468        // account.
10469        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10470            if (cpuAbiOverride == null && pkg.packageName != null) {
10471                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10472                        " for package " + pkg.packageName);
10473            }
10474        }
10475
10476        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10477        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10478        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10479
10480        // Copy the derived override back to the parsed package, so that we can
10481        // update the package settings accordingly.
10482        pkg.cpuAbiOverride = cpuAbiOverride;
10483
10484        if (DEBUG_ABI_SELECTION) {
10485            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10486                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10487                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10488        }
10489
10490        // Push the derived path down into PackageSettings so we know what to
10491        // clean up at uninstall time.
10492        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10493
10494        if (DEBUG_ABI_SELECTION) {
10495            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10496                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10497                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10498        }
10499
10500        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10501            // We don't do this here during boot because we can do it all
10502            // at once after scanning all existing packages.
10503            //
10504            // We also do this *before* we perform dexopt on this package, so that
10505            // we can avoid redundant dexopts, and also to make sure we've got the
10506            // code and package path correct.
10507            changedAbiCodePath =
10508                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10509        }
10510
10511        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10512                android.Manifest.permission.FACTORY_TEST)) {
10513            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10514        }
10515
10516        if (isSystemApp(pkg)) {
10517            pkgSetting.isOrphaned = true;
10518        }
10519
10520        // Take care of first install / last update times.
10521        final long scanFileTime = getLastModifiedTime(pkg);
10522        if (currentTime != 0) {
10523            if (pkgSetting.firstInstallTime == 0) {
10524                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10525            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10526                pkgSetting.lastUpdateTime = currentTime;
10527            }
10528        } else if (pkgSetting.firstInstallTime == 0) {
10529            // We need *something*.  Take time time stamp of the file.
10530            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10531        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10532            if (scanFileTime != pkgSetting.timeStamp) {
10533                // A package on the system image has changed; consider this
10534                // to be an update.
10535                pkgSetting.lastUpdateTime = scanFileTime;
10536            }
10537        }
10538        pkgSetting.setTimeStamp(scanFileTime);
10539
10540        pkgSetting.pkg = pkg;
10541        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10542        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10543            pkgSetting.versionCode = pkg.getLongVersionCode();
10544        }
10545        // Update volume if needed
10546        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10547        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10548            Slog.i(PackageManagerService.TAG,
10549                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10550                    + " package " + pkg.packageName
10551                    + " volume from " + pkgSetting.volumeUuid
10552                    + " to " + volumeUuid);
10553            pkgSetting.volumeUuid = volumeUuid;
10554        }
10555
10556        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10557    }
10558
10559    /**
10560     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10561     */
10562    private static boolean apkHasCode(String fileName) {
10563        StrictJarFile jarFile = null;
10564        try {
10565            jarFile = new StrictJarFile(fileName,
10566                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10567            return jarFile.findEntry("classes.dex") != null;
10568        } catch (IOException ignore) {
10569        } finally {
10570            try {
10571                if (jarFile != null) {
10572                    jarFile.close();
10573                }
10574            } catch (IOException ignore) {}
10575        }
10576        return false;
10577    }
10578
10579    /**
10580     * Enforces code policy for the package. This ensures that if an APK has
10581     * declared hasCode="true" in its manifest that the APK actually contains
10582     * code.
10583     *
10584     * @throws PackageManagerException If bytecode could not be found when it should exist
10585     */
10586    private static void assertCodePolicy(PackageParser.Package pkg)
10587            throws PackageManagerException {
10588        final boolean shouldHaveCode =
10589                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10590        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10591            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10592                    "Package " + pkg.baseCodePath + " code is missing");
10593        }
10594
10595        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10596            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10597                final boolean splitShouldHaveCode =
10598                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10599                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10600                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10601                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10602                }
10603            }
10604        }
10605    }
10606
10607    /**
10608     * Applies policy to the parsed package based upon the given policy flags.
10609     * Ensures the package is in a good state.
10610     * <p>
10611     * Implementation detail: This method must NOT have any side effect. It would
10612     * ideally be static, but, it requires locks to read system state.
10613     */
10614    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10615            final @ScanFlags int scanFlags) {
10616        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10617            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10618            if (pkg.applicationInfo.isDirectBootAware()) {
10619                // we're direct boot aware; set for all components
10620                for (PackageParser.Service s : pkg.services) {
10621                    s.info.encryptionAware = s.info.directBootAware = true;
10622                }
10623                for (PackageParser.Provider p : pkg.providers) {
10624                    p.info.encryptionAware = p.info.directBootAware = true;
10625                }
10626                for (PackageParser.Activity a : pkg.activities) {
10627                    a.info.encryptionAware = a.info.directBootAware = true;
10628                }
10629                for (PackageParser.Activity r : pkg.receivers) {
10630                    r.info.encryptionAware = r.info.directBootAware = true;
10631                }
10632            }
10633            if (compressedFileExists(pkg.codePath)) {
10634                pkg.isStub = true;
10635            }
10636        } else {
10637            // non system apps can't be flagged as core
10638            pkg.coreApp = false;
10639            // clear flags not applicable to regular apps
10640            pkg.applicationInfo.flags &=
10641                    ~ApplicationInfo.FLAG_PERSISTENT;
10642            pkg.applicationInfo.privateFlags &=
10643                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10644            pkg.applicationInfo.privateFlags &=
10645                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10646            // cap permission priorities
10647            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10648                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10649                    pkg.permissionGroups.get(i).info.priority = 0;
10650                }
10651            }
10652        }
10653        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10654            // clear protected broadcasts
10655            pkg.protectedBroadcasts = null;
10656            // ignore export request for single user receivers
10657            if (pkg.receivers != null) {
10658                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10659                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10660                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10661                        receiver.info.exported = false;
10662                    }
10663                }
10664            }
10665            // ignore export request for single user services
10666            if (pkg.services != null) {
10667                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10668                    final PackageParser.Service service = pkg.services.get(i);
10669                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10670                        service.info.exported = false;
10671                    }
10672                }
10673            }
10674            // ignore export request for single user providers
10675            if (pkg.providers != null) {
10676                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10677                    final PackageParser.Provider provider = pkg.providers.get(i);
10678                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10679                        provider.info.exported = false;
10680                    }
10681                }
10682            }
10683        }
10684
10685        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10686            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10687        }
10688
10689        if ((scanFlags & SCAN_AS_OEM) != 0) {
10690            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10691        }
10692
10693        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10694            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10695        }
10696
10697        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10698            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10699        }
10700
10701        if (!isSystemApp(pkg)) {
10702            // Only system apps can use these features.
10703            pkg.mOriginalPackages = null;
10704            pkg.mRealPackage = null;
10705            pkg.mAdoptPermissions = null;
10706        }
10707    }
10708
10709    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10710            throws PackageManagerException {
10711        if (object == null) {
10712            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10713        }
10714        return object;
10715    }
10716
10717    /**
10718     * Asserts the parsed package is valid according to the given policy. If the
10719     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10720     * <p>
10721     * Implementation detail: This method must NOT have any side effects. It would
10722     * ideally be static, but, it requires locks to read system state.
10723     *
10724     * @throws PackageManagerException If the package fails any of the validation checks
10725     */
10726    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10727            final @ScanFlags int scanFlags)
10728                    throws PackageManagerException {
10729        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10730            assertCodePolicy(pkg);
10731        }
10732
10733        if (pkg.applicationInfo.getCodePath() == null ||
10734                pkg.applicationInfo.getResourcePath() == null) {
10735            // Bail out. The resource and code paths haven't been set.
10736            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10737                    "Code and resource paths haven't been set correctly");
10738        }
10739
10740        // Make sure we're not adding any bogus keyset info
10741        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10742        ksms.assertScannedPackageValid(pkg);
10743
10744        synchronized (mPackages) {
10745            // The special "android" package can only be defined once
10746            if (pkg.packageName.equals("android")) {
10747                if (mAndroidApplication != null) {
10748                    Slog.w(TAG, "*************************************************");
10749                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10750                    Slog.w(TAG, " codePath=" + pkg.codePath);
10751                    Slog.w(TAG, "*************************************************");
10752                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10753                            "Core android package being redefined.  Skipping.");
10754                }
10755            }
10756
10757            // A package name must be unique; don't allow duplicates
10758            if (mPackages.containsKey(pkg.packageName)) {
10759                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10760                        "Application package " + pkg.packageName
10761                        + " already installed.  Skipping duplicate.");
10762            }
10763
10764            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10765                // Static libs have a synthetic package name containing the version
10766                // but we still want the base name to be unique.
10767                if (mPackages.containsKey(pkg.manifestPackageName)) {
10768                    throw new PackageManagerException(
10769                            "Duplicate static shared lib provider package");
10770                }
10771
10772                // Static shared libraries should have at least O target SDK
10773                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10774                    throw new PackageManagerException(
10775                            "Packages declaring static-shared libs must target O SDK or higher");
10776                }
10777
10778                // Package declaring static a shared lib cannot be instant apps
10779                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10780                    throw new PackageManagerException(
10781                            "Packages declaring static-shared libs cannot be instant apps");
10782                }
10783
10784                // Package declaring static a shared lib cannot be renamed since the package
10785                // name is synthetic and apps can't code around package manager internals.
10786                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10787                    throw new PackageManagerException(
10788                            "Packages declaring static-shared libs cannot be renamed");
10789                }
10790
10791                // Package declaring static a shared lib cannot declare child packages
10792                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10793                    throw new PackageManagerException(
10794                            "Packages declaring static-shared libs cannot have child packages");
10795                }
10796
10797                // Package declaring static a shared lib cannot declare dynamic libs
10798                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10799                    throw new PackageManagerException(
10800                            "Packages declaring static-shared libs cannot declare dynamic libs");
10801                }
10802
10803                // Package declaring static a shared lib cannot declare shared users
10804                if (pkg.mSharedUserId != null) {
10805                    throw new PackageManagerException(
10806                            "Packages declaring static-shared libs cannot declare shared users");
10807                }
10808
10809                // Static shared libs cannot declare activities
10810                if (!pkg.activities.isEmpty()) {
10811                    throw new PackageManagerException(
10812                            "Static shared libs cannot declare activities");
10813                }
10814
10815                // Static shared libs cannot declare services
10816                if (!pkg.services.isEmpty()) {
10817                    throw new PackageManagerException(
10818                            "Static shared libs cannot declare services");
10819                }
10820
10821                // Static shared libs cannot declare providers
10822                if (!pkg.providers.isEmpty()) {
10823                    throw new PackageManagerException(
10824                            "Static shared libs cannot declare content providers");
10825                }
10826
10827                // Static shared libs cannot declare receivers
10828                if (!pkg.receivers.isEmpty()) {
10829                    throw new PackageManagerException(
10830                            "Static shared libs cannot declare broadcast receivers");
10831                }
10832
10833                // Static shared libs cannot declare permission groups
10834                if (!pkg.permissionGroups.isEmpty()) {
10835                    throw new PackageManagerException(
10836                            "Static shared libs cannot declare permission groups");
10837                }
10838
10839                // Static shared libs cannot declare permissions
10840                if (!pkg.permissions.isEmpty()) {
10841                    throw new PackageManagerException(
10842                            "Static shared libs cannot declare permissions");
10843                }
10844
10845                // Static shared libs cannot declare protected broadcasts
10846                if (pkg.protectedBroadcasts != null) {
10847                    throw new PackageManagerException(
10848                            "Static shared libs cannot declare protected broadcasts");
10849                }
10850
10851                // Static shared libs cannot be overlay targets
10852                if (pkg.mOverlayTarget != null) {
10853                    throw new PackageManagerException(
10854                            "Static shared libs cannot be overlay targets");
10855                }
10856
10857                // The version codes must be ordered as lib versions
10858                long minVersionCode = Long.MIN_VALUE;
10859                long maxVersionCode = Long.MAX_VALUE;
10860
10861                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10862                        pkg.staticSharedLibName);
10863                if (versionedLib != null) {
10864                    final int versionCount = versionedLib.size();
10865                    for (int i = 0; i < versionCount; i++) {
10866                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10867                        final long libVersionCode = libInfo.getDeclaringPackage()
10868                                .getLongVersionCode();
10869                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10870                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10871                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10872                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10873                        } else {
10874                            minVersionCode = maxVersionCode = libVersionCode;
10875                            break;
10876                        }
10877                    }
10878                }
10879                if (pkg.getLongVersionCode() < minVersionCode
10880                        || pkg.getLongVersionCode() > maxVersionCode) {
10881                    throw new PackageManagerException("Static shared"
10882                            + " lib version codes must be ordered as lib versions");
10883                }
10884            }
10885
10886            // Only privileged apps and updated privileged apps can add child packages.
10887            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10888                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10889                    throw new PackageManagerException("Only privileged apps can add child "
10890                            + "packages. Ignoring package " + pkg.packageName);
10891                }
10892                final int childCount = pkg.childPackages.size();
10893                for (int i = 0; i < childCount; i++) {
10894                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10895                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10896                            childPkg.packageName)) {
10897                        throw new PackageManagerException("Can't override child of "
10898                                + "another disabled app. Ignoring package " + pkg.packageName);
10899                    }
10900                }
10901            }
10902
10903            // If we're only installing presumed-existing packages, require that the
10904            // scanned APK is both already known and at the path previously established
10905            // for it.  Previously unknown packages we pick up normally, but if we have an
10906            // a priori expectation about this package's install presence, enforce it.
10907            // With a singular exception for new system packages. When an OTA contains
10908            // a new system package, we allow the codepath to change from a system location
10909            // to the user-installed location. If we don't allow this change, any newer,
10910            // user-installed version of the application will be ignored.
10911            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10912                if (mExpectingBetter.containsKey(pkg.packageName)) {
10913                    logCriticalInfo(Log.WARN,
10914                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10915                } else {
10916                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10917                    if (known != null) {
10918                        if (DEBUG_PACKAGE_SCANNING) {
10919                            Log.d(TAG, "Examining " + pkg.codePath
10920                                    + " and requiring known paths " + known.codePathString
10921                                    + " & " + known.resourcePathString);
10922                        }
10923                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10924                                || !pkg.applicationInfo.getResourcePath().equals(
10925                                        known.resourcePathString)) {
10926                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10927                                    "Application package " + pkg.packageName
10928                                    + " found at " + pkg.applicationInfo.getCodePath()
10929                                    + " but expected at " + known.codePathString
10930                                    + "; ignoring.");
10931                        }
10932                    } else {
10933                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10934                                "Application package " + pkg.packageName
10935                                + " not found; ignoring.");
10936                    }
10937                }
10938            }
10939
10940            // Verify that this new package doesn't have any content providers
10941            // that conflict with existing packages.  Only do this if the
10942            // package isn't already installed, since we don't want to break
10943            // things that are installed.
10944            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10945                final int N = pkg.providers.size();
10946                int i;
10947                for (i=0; i<N; i++) {
10948                    PackageParser.Provider p = pkg.providers.get(i);
10949                    if (p.info.authority != null) {
10950                        String names[] = p.info.authority.split(";");
10951                        for (int j = 0; j < names.length; j++) {
10952                            if (mProvidersByAuthority.containsKey(names[j])) {
10953                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10954                                final String otherPackageName =
10955                                        ((other != null && other.getComponentName() != null) ?
10956                                                other.getComponentName().getPackageName() : "?");
10957                                throw new PackageManagerException(
10958                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10959                                        "Can't install because provider name " + names[j]
10960                                                + " (in package " + pkg.applicationInfo.packageName
10961                                                + ") is already used by " + otherPackageName);
10962                            }
10963                        }
10964                    }
10965                }
10966            }
10967
10968            // Verify that packages sharing a user with a privileged app are marked as privileged.
10969            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
10970                SharedUserSetting sharedUserSetting = null;
10971                try {
10972                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
10973                } catch (PackageManagerException ignore) {}
10974                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10975                    // Exempt SharedUsers signed with the platform key.
10976                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10977                    if ((platformPkgSetting.signatures.mSigningDetails
10978                            != PackageParser.SigningDetails.UNKNOWN)
10979                            && (compareSignatures(
10980                                    platformPkgSetting.signatures.mSigningDetails.signatures,
10981                                    pkg.mSigningDetails.signatures)
10982                                            != PackageManager.SIGNATURE_MATCH)) {
10983                        throw new PackageManagerException("Apps that share a user with a " +
10984                                "privileged app must themselves be marked as privileged. " +
10985                                pkg.packageName + " shares privileged user " +
10986                                pkg.mSharedUserId + ".");
10987                    }
10988                }
10989            }
10990
10991            // Apply policies specific for runtime resource overlays (RROs).
10992            if (pkg.mOverlayTarget != null) {
10993                // System overlays have some restrictions on their use of the 'static' state.
10994                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10995                    // We are scanning a system overlay. This can be the first scan of the
10996                    // system/vendor/oem partition, or an update to the system overlay.
10997                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10998                        // This must be an update to a system overlay.
10999                        final PackageSetting previousPkg = assertNotNull(
11000                                mSettings.getPackageLPr(pkg.packageName),
11001                                "previous package state not present");
11002
11003                        // Static overlays cannot be updated.
11004                        if (previousPkg.pkg.mOverlayIsStatic) {
11005                            throw new PackageManagerException("Overlay " + pkg.packageName +
11006                                    " is static and cannot be upgraded.");
11007                        // Non-static overlays cannot be converted to static overlays.
11008                        } else if (pkg.mOverlayIsStatic) {
11009                            throw new PackageManagerException("Overlay " + pkg.packageName +
11010                                    " cannot be upgraded into a static overlay.");
11011                        }
11012                    }
11013                } else {
11014                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11015                    if (pkg.mOverlayIsStatic) {
11016                        throw new PackageManagerException("Overlay " + pkg.packageName +
11017                                " is static but not pre-installed.");
11018                    }
11019
11020                    // The only case where we allow installation of a non-system overlay is when
11021                    // its signature is signed with the platform certificate.
11022                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11023                    if ((platformPkgSetting.signatures.mSigningDetails
11024                            != PackageParser.SigningDetails.UNKNOWN)
11025                            && (compareSignatures(
11026                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11027                                    pkg.mSigningDetails.signatures)
11028                                            != PackageManager.SIGNATURE_MATCH)) {
11029                        throw new PackageManagerException("Overlay " + pkg.packageName +
11030                                " must be signed with the platform certificate.");
11031                    }
11032                }
11033            }
11034        }
11035    }
11036
11037    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11038            int type, String declaringPackageName, long declaringVersionCode) {
11039        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11040        if (versionedLib == null) {
11041            versionedLib = new LongSparseArray<>();
11042            mSharedLibraries.put(name, versionedLib);
11043            if (type == SharedLibraryInfo.TYPE_STATIC) {
11044                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11045            }
11046        } else if (versionedLib.indexOfKey(version) >= 0) {
11047            return false;
11048        }
11049        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11050                version, type, declaringPackageName, declaringVersionCode);
11051        versionedLib.put(version, libEntry);
11052        return true;
11053    }
11054
11055    private boolean removeSharedLibraryLPw(String name, long version) {
11056        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11057        if (versionedLib == null) {
11058            return false;
11059        }
11060        final int libIdx = versionedLib.indexOfKey(version);
11061        if (libIdx < 0) {
11062            return false;
11063        }
11064        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11065        versionedLib.remove(version);
11066        if (versionedLib.size() <= 0) {
11067            mSharedLibraries.remove(name);
11068            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11069                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11070                        .getPackageName());
11071            }
11072        }
11073        return true;
11074    }
11075
11076    /**
11077     * Adds a scanned package to the system. When this method is finished, the package will
11078     * be available for query, resolution, etc...
11079     */
11080    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11081            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11082        final String pkgName = pkg.packageName;
11083        if (mCustomResolverComponentName != null &&
11084                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11085            setUpCustomResolverActivity(pkg);
11086        }
11087
11088        if (pkg.packageName.equals("android")) {
11089            synchronized (mPackages) {
11090                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11091                    // Set up information for our fall-back user intent resolution activity.
11092                    mPlatformPackage = pkg;
11093                    pkg.mVersionCode = mSdkVersion;
11094                    pkg.mVersionCodeMajor = 0;
11095                    mAndroidApplication = pkg.applicationInfo;
11096                    if (!mResolverReplaced) {
11097                        mResolveActivity.applicationInfo = mAndroidApplication;
11098                        mResolveActivity.name = ResolverActivity.class.getName();
11099                        mResolveActivity.packageName = mAndroidApplication.packageName;
11100                        mResolveActivity.processName = "system:ui";
11101                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11102                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11103                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11104                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11105                        mResolveActivity.exported = true;
11106                        mResolveActivity.enabled = true;
11107                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11108                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11109                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11110                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11111                                | ActivityInfo.CONFIG_ORIENTATION
11112                                | ActivityInfo.CONFIG_KEYBOARD
11113                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11114                        mResolveInfo.activityInfo = mResolveActivity;
11115                        mResolveInfo.priority = 0;
11116                        mResolveInfo.preferredOrder = 0;
11117                        mResolveInfo.match = 0;
11118                        mResolveComponentName = new ComponentName(
11119                                mAndroidApplication.packageName, mResolveActivity.name);
11120                    }
11121                }
11122            }
11123        }
11124
11125        ArrayList<PackageParser.Package> clientLibPkgs = null;
11126        // writer
11127        synchronized (mPackages) {
11128            boolean hasStaticSharedLibs = false;
11129
11130            // Any app can add new static shared libraries
11131            if (pkg.staticSharedLibName != null) {
11132                // Static shared libs don't allow renaming as they have synthetic package
11133                // names to allow install of multiple versions, so use name from manifest.
11134                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11135                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11136                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11137                    hasStaticSharedLibs = true;
11138                } else {
11139                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11140                                + pkg.staticSharedLibName + " already exists; skipping");
11141                }
11142                // Static shared libs cannot be updated once installed since they
11143                // use synthetic package name which includes the version code, so
11144                // not need to update other packages's shared lib dependencies.
11145            }
11146
11147            if (!hasStaticSharedLibs
11148                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11149                // Only system apps can add new dynamic shared libraries.
11150                if (pkg.libraryNames != null) {
11151                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11152                        String name = pkg.libraryNames.get(i);
11153                        boolean allowed = false;
11154                        if (pkg.isUpdatedSystemApp()) {
11155                            // New library entries can only be added through the
11156                            // system image.  This is important to get rid of a lot
11157                            // of nasty edge cases: for example if we allowed a non-
11158                            // system update of the app to add a library, then uninstalling
11159                            // the update would make the library go away, and assumptions
11160                            // we made such as through app install filtering would now
11161                            // have allowed apps on the device which aren't compatible
11162                            // with it.  Better to just have the restriction here, be
11163                            // conservative, and create many fewer cases that can negatively
11164                            // impact the user experience.
11165                            final PackageSetting sysPs = mSettings
11166                                    .getDisabledSystemPkgLPr(pkg.packageName);
11167                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11168                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11169                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11170                                        allowed = true;
11171                                        break;
11172                                    }
11173                                }
11174                            }
11175                        } else {
11176                            allowed = true;
11177                        }
11178                        if (allowed) {
11179                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11180                                    SharedLibraryInfo.VERSION_UNDEFINED,
11181                                    SharedLibraryInfo.TYPE_DYNAMIC,
11182                                    pkg.packageName, pkg.getLongVersionCode())) {
11183                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11184                                        + name + " already exists; skipping");
11185                            }
11186                        } else {
11187                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11188                                    + name + " that is not declared on system image; skipping");
11189                        }
11190                    }
11191
11192                    if ((scanFlags & SCAN_BOOTING) == 0) {
11193                        // If we are not booting, we need to update any applications
11194                        // that are clients of our shared library.  If we are booting,
11195                        // this will all be done once the scan is complete.
11196                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11197                    }
11198                }
11199            }
11200        }
11201
11202        if ((scanFlags & SCAN_BOOTING) != 0) {
11203            // No apps can run during boot scan, so they don't need to be frozen
11204        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11205            // Caller asked to not kill app, so it's probably not frozen
11206        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11207            // Caller asked us to ignore frozen check for some reason; they
11208            // probably didn't know the package name
11209        } else {
11210            // We're doing major surgery on this package, so it better be frozen
11211            // right now to keep it from launching
11212            checkPackageFrozen(pkgName);
11213        }
11214
11215        // Also need to kill any apps that are dependent on the library.
11216        if (clientLibPkgs != null) {
11217            for (int i=0; i<clientLibPkgs.size(); i++) {
11218                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11219                killApplication(clientPkg.applicationInfo.packageName,
11220                        clientPkg.applicationInfo.uid, "update lib");
11221            }
11222        }
11223
11224        // writer
11225        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11226
11227        synchronized (mPackages) {
11228            // We don't expect installation to fail beyond this point
11229
11230            // Add the new setting to mSettings
11231            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11232            // Add the new setting to mPackages
11233            mPackages.put(pkg.applicationInfo.packageName, pkg);
11234            // Make sure we don't accidentally delete its data.
11235            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11236            while (iter.hasNext()) {
11237                PackageCleanItem item = iter.next();
11238                if (pkgName.equals(item.packageName)) {
11239                    iter.remove();
11240                }
11241            }
11242
11243            // Add the package's KeySets to the global KeySetManagerService
11244            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11245            ksms.addScannedPackageLPw(pkg);
11246
11247            int N = pkg.providers.size();
11248            StringBuilder r = null;
11249            int i;
11250            for (i=0; i<N; i++) {
11251                PackageParser.Provider p = pkg.providers.get(i);
11252                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11253                        p.info.processName);
11254                mProviders.addProvider(p);
11255                p.syncable = p.info.isSyncable;
11256                if (p.info.authority != null) {
11257                    String names[] = p.info.authority.split(";");
11258                    p.info.authority = null;
11259                    for (int j = 0; j < names.length; j++) {
11260                        if (j == 1 && p.syncable) {
11261                            // We only want the first authority for a provider to possibly be
11262                            // syncable, so if we already added this provider using a different
11263                            // authority clear the syncable flag. We copy the provider before
11264                            // changing it because the mProviders object contains a reference
11265                            // to a provider that we don't want to change.
11266                            // Only do this for the second authority since the resulting provider
11267                            // object can be the same for all future authorities for this provider.
11268                            p = new PackageParser.Provider(p);
11269                            p.syncable = false;
11270                        }
11271                        if (!mProvidersByAuthority.containsKey(names[j])) {
11272                            mProvidersByAuthority.put(names[j], p);
11273                            if (p.info.authority == null) {
11274                                p.info.authority = names[j];
11275                            } else {
11276                                p.info.authority = p.info.authority + ";" + names[j];
11277                            }
11278                            if (DEBUG_PACKAGE_SCANNING) {
11279                                if (chatty)
11280                                    Log.d(TAG, "Registered content provider: " + names[j]
11281                                            + ", className = " + p.info.name + ", isSyncable = "
11282                                            + p.info.isSyncable);
11283                            }
11284                        } else {
11285                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11286                            Slog.w(TAG, "Skipping provider name " + names[j] +
11287                                    " (in package " + pkg.applicationInfo.packageName +
11288                                    "): name already used by "
11289                                    + ((other != null && other.getComponentName() != null)
11290                                            ? other.getComponentName().getPackageName() : "?"));
11291                        }
11292                    }
11293                }
11294                if (chatty) {
11295                    if (r == null) {
11296                        r = new StringBuilder(256);
11297                    } else {
11298                        r.append(' ');
11299                    }
11300                    r.append(p.info.name);
11301                }
11302            }
11303            if (r != null) {
11304                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11305            }
11306
11307            N = pkg.services.size();
11308            r = null;
11309            for (i=0; i<N; i++) {
11310                PackageParser.Service s = pkg.services.get(i);
11311                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11312                        s.info.processName);
11313                mServices.addService(s);
11314                if (chatty) {
11315                    if (r == null) {
11316                        r = new StringBuilder(256);
11317                    } else {
11318                        r.append(' ');
11319                    }
11320                    r.append(s.info.name);
11321                }
11322            }
11323            if (r != null) {
11324                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11325            }
11326
11327            N = pkg.receivers.size();
11328            r = null;
11329            for (i=0; i<N; i++) {
11330                PackageParser.Activity a = pkg.receivers.get(i);
11331                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11332                        a.info.processName);
11333                mReceivers.addActivity(a, "receiver");
11334                if (chatty) {
11335                    if (r == null) {
11336                        r = new StringBuilder(256);
11337                    } else {
11338                        r.append(' ');
11339                    }
11340                    r.append(a.info.name);
11341                }
11342            }
11343            if (r != null) {
11344                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11345            }
11346
11347            N = pkg.activities.size();
11348            r = null;
11349            for (i=0; i<N; i++) {
11350                PackageParser.Activity a = pkg.activities.get(i);
11351                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11352                        a.info.processName);
11353                mActivities.addActivity(a, "activity");
11354                if (chatty) {
11355                    if (r == null) {
11356                        r = new StringBuilder(256);
11357                    } else {
11358                        r.append(' ');
11359                    }
11360                    r.append(a.info.name);
11361                }
11362            }
11363            if (r != null) {
11364                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11365            }
11366
11367            // Don't allow ephemeral applications to define new permissions groups.
11368            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11369                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11370                        + " ignored: instant apps cannot define new permission groups.");
11371            } else {
11372                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11373            }
11374
11375            // Don't allow ephemeral applications to define new permissions.
11376            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11377                Slog.w(TAG, "Permissions from package " + pkg.packageName
11378                        + " ignored: instant apps cannot define new permissions.");
11379            } else {
11380                mPermissionManager.addAllPermissions(pkg, chatty);
11381            }
11382
11383            N = pkg.instrumentation.size();
11384            r = null;
11385            for (i=0; i<N; i++) {
11386                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11387                a.info.packageName = pkg.applicationInfo.packageName;
11388                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11389                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11390                a.info.splitNames = pkg.splitNames;
11391                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11392                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11393                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11394                a.info.dataDir = pkg.applicationInfo.dataDir;
11395                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11396                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11397                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11398                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11399                mInstrumentation.put(a.getComponentName(), a);
11400                if (chatty) {
11401                    if (r == null) {
11402                        r = new StringBuilder(256);
11403                    } else {
11404                        r.append(' ');
11405                    }
11406                    r.append(a.info.name);
11407                }
11408            }
11409            if (r != null) {
11410                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11411            }
11412
11413            if (pkg.protectedBroadcasts != null) {
11414                N = pkg.protectedBroadcasts.size();
11415                synchronized (mProtectedBroadcasts) {
11416                    for (i = 0; i < N; i++) {
11417                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11418                    }
11419                }
11420            }
11421        }
11422
11423        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11424    }
11425
11426    /**
11427     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11428     * is derived purely on the basis of the contents of {@code scanFile} and
11429     * {@code cpuAbiOverride}.
11430     *
11431     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11432     */
11433    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11434            boolean extractLibs)
11435                    throws PackageManagerException {
11436        // Give ourselves some initial paths; we'll come back for another
11437        // pass once we've determined ABI below.
11438        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11439
11440        // We would never need to extract libs for forward-locked and external packages,
11441        // since the container service will do it for us. We shouldn't attempt to
11442        // extract libs from system app when it was not updated.
11443        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11444                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11445            extractLibs = false;
11446        }
11447
11448        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11449        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11450
11451        NativeLibraryHelper.Handle handle = null;
11452        try {
11453            handle = NativeLibraryHelper.Handle.create(pkg);
11454            // TODO(multiArch): This can be null for apps that didn't go through the
11455            // usual installation process. We can calculate it again, like we
11456            // do during install time.
11457            //
11458            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11459            // unnecessary.
11460            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11461
11462            // Null out the abis so that they can be recalculated.
11463            pkg.applicationInfo.primaryCpuAbi = null;
11464            pkg.applicationInfo.secondaryCpuAbi = null;
11465            if (isMultiArch(pkg.applicationInfo)) {
11466                // Warn if we've set an abiOverride for multi-lib packages..
11467                // By definition, we need to copy both 32 and 64 bit libraries for
11468                // such packages.
11469                if (pkg.cpuAbiOverride != null
11470                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11471                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11472                }
11473
11474                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11475                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11476                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11477                    if (extractLibs) {
11478                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11479                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11480                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11481                                useIsaSpecificSubdirs);
11482                    } else {
11483                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11484                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11485                    }
11486                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11487                }
11488
11489                // Shared library native code should be in the APK zip aligned
11490                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11491                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11492                            "Shared library native lib extraction not supported");
11493                }
11494
11495                maybeThrowExceptionForMultiArchCopy(
11496                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11497
11498                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11499                    if (extractLibs) {
11500                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11501                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11502                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11503                                useIsaSpecificSubdirs);
11504                    } else {
11505                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11506                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11507                    }
11508                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11509                }
11510
11511                maybeThrowExceptionForMultiArchCopy(
11512                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11513
11514                if (abi64 >= 0) {
11515                    // Shared library native libs should be in the APK zip aligned
11516                    if (extractLibs && pkg.isLibrary()) {
11517                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11518                                "Shared library native lib extraction not supported");
11519                    }
11520                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11521                }
11522
11523                if (abi32 >= 0) {
11524                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11525                    if (abi64 >= 0) {
11526                        if (pkg.use32bitAbi) {
11527                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11528                            pkg.applicationInfo.primaryCpuAbi = abi;
11529                        } else {
11530                            pkg.applicationInfo.secondaryCpuAbi = abi;
11531                        }
11532                    } else {
11533                        pkg.applicationInfo.primaryCpuAbi = abi;
11534                    }
11535                }
11536            } else {
11537                String[] abiList = (cpuAbiOverride != null) ?
11538                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11539
11540                // Enable gross and lame hacks for apps that are built with old
11541                // SDK tools. We must scan their APKs for renderscript bitcode and
11542                // not launch them if it's present. Don't bother checking on devices
11543                // that don't have 64 bit support.
11544                boolean needsRenderScriptOverride = false;
11545                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11546                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11547                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11548                    needsRenderScriptOverride = true;
11549                }
11550
11551                final int copyRet;
11552                if (extractLibs) {
11553                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11554                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11555                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11556                } else {
11557                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11558                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11559                }
11560                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11561
11562                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11563                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11564                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11565                }
11566
11567                if (copyRet >= 0) {
11568                    // Shared libraries that have native libs must be multi-architecture
11569                    if (pkg.isLibrary()) {
11570                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11571                                "Shared library with native libs must be multiarch");
11572                    }
11573                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11574                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11575                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11576                } else if (needsRenderScriptOverride) {
11577                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11578                }
11579            }
11580        } catch (IOException ioe) {
11581            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11582        } finally {
11583            IoUtils.closeQuietly(handle);
11584        }
11585
11586        // Now that we've calculated the ABIs and determined if it's an internal app,
11587        // we will go ahead and populate the nativeLibraryPath.
11588        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11589    }
11590
11591    /**
11592     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11593     * i.e, so that all packages can be run inside a single process if required.
11594     *
11595     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11596     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11597     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11598     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11599     * updating a package that belongs to a shared user.
11600     *
11601     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11602     * adds unnecessary complexity.
11603     */
11604    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11605            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11606        List<String> changedAbiCodePath = null;
11607        String requiredInstructionSet = null;
11608        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11609            requiredInstructionSet = VMRuntime.getInstructionSet(
11610                     scannedPackage.applicationInfo.primaryCpuAbi);
11611        }
11612
11613        PackageSetting requirer = null;
11614        for (PackageSetting ps : packagesForUser) {
11615            // If packagesForUser contains scannedPackage, we skip it. This will happen
11616            // when scannedPackage is an update of an existing package. Without this check,
11617            // we will never be able to change the ABI of any package belonging to a shared
11618            // user, even if it's compatible with other packages.
11619            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11620                if (ps.primaryCpuAbiString == null) {
11621                    continue;
11622                }
11623
11624                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11625                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11626                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11627                    // this but there's not much we can do.
11628                    String errorMessage = "Instruction set mismatch, "
11629                            + ((requirer == null) ? "[caller]" : requirer)
11630                            + " requires " + requiredInstructionSet + " whereas " + ps
11631                            + " requires " + instructionSet;
11632                    Slog.w(TAG, errorMessage);
11633                }
11634
11635                if (requiredInstructionSet == null) {
11636                    requiredInstructionSet = instructionSet;
11637                    requirer = ps;
11638                }
11639            }
11640        }
11641
11642        if (requiredInstructionSet != null) {
11643            String adjustedAbi;
11644            if (requirer != null) {
11645                // requirer != null implies that either scannedPackage was null or that scannedPackage
11646                // did not require an ABI, in which case we have to adjust scannedPackage to match
11647                // the ABI of the set (which is the same as requirer's ABI)
11648                adjustedAbi = requirer.primaryCpuAbiString;
11649                if (scannedPackage != null) {
11650                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11651                }
11652            } else {
11653                // requirer == null implies that we're updating all ABIs in the set to
11654                // match scannedPackage.
11655                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11656            }
11657
11658            for (PackageSetting ps : packagesForUser) {
11659                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11660                    if (ps.primaryCpuAbiString != null) {
11661                        continue;
11662                    }
11663
11664                    ps.primaryCpuAbiString = adjustedAbi;
11665                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11666                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11667                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11668                        if (DEBUG_ABI_SELECTION) {
11669                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11670                                    + " (requirer="
11671                                    + (requirer != null ? requirer.pkg : "null")
11672                                    + ", scannedPackage="
11673                                    + (scannedPackage != null ? scannedPackage : "null")
11674                                    + ")");
11675                        }
11676                        if (changedAbiCodePath == null) {
11677                            changedAbiCodePath = new ArrayList<>();
11678                        }
11679                        changedAbiCodePath.add(ps.codePathString);
11680                    }
11681                }
11682            }
11683        }
11684        return changedAbiCodePath;
11685    }
11686
11687    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11688        synchronized (mPackages) {
11689            mResolverReplaced = true;
11690            // Set up information for custom user intent resolution activity.
11691            mResolveActivity.applicationInfo = pkg.applicationInfo;
11692            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11693            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11694            mResolveActivity.processName = pkg.applicationInfo.packageName;
11695            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11696            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11697                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11698            mResolveActivity.theme = 0;
11699            mResolveActivity.exported = true;
11700            mResolveActivity.enabled = true;
11701            mResolveInfo.activityInfo = mResolveActivity;
11702            mResolveInfo.priority = 0;
11703            mResolveInfo.preferredOrder = 0;
11704            mResolveInfo.match = 0;
11705            mResolveComponentName = mCustomResolverComponentName;
11706            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11707                    mResolveComponentName);
11708        }
11709    }
11710
11711    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11712        if (installerActivity == null) {
11713            if (DEBUG_INSTANT) {
11714                Slog.d(TAG, "Clear ephemeral installer activity");
11715            }
11716            mInstantAppInstallerActivity = null;
11717            return;
11718        }
11719
11720        if (DEBUG_INSTANT) {
11721            Slog.d(TAG, "Set ephemeral installer activity: "
11722                    + installerActivity.getComponentName());
11723        }
11724        // Set up information for ephemeral installer activity
11725        mInstantAppInstallerActivity = installerActivity;
11726        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11727                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11728        mInstantAppInstallerActivity.exported = true;
11729        mInstantAppInstallerActivity.enabled = true;
11730        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11731        mInstantAppInstallerInfo.priority = 1;
11732        mInstantAppInstallerInfo.preferredOrder = 1;
11733        mInstantAppInstallerInfo.isDefault = true;
11734        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11735                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11736    }
11737
11738    private static String calculateBundledApkRoot(final String codePathString) {
11739        final File codePath = new File(codePathString);
11740        final File codeRoot;
11741        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11742            codeRoot = Environment.getRootDirectory();
11743        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11744            codeRoot = Environment.getOemDirectory();
11745        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11746            codeRoot = Environment.getVendorDirectory();
11747        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11748            codeRoot = Environment.getProductDirectory();
11749        } else {
11750            // Unrecognized code path; take its top real segment as the apk root:
11751            // e.g. /something/app/blah.apk => /something
11752            try {
11753                File f = codePath.getCanonicalFile();
11754                File parent = f.getParentFile();    // non-null because codePath is a file
11755                File tmp;
11756                while ((tmp = parent.getParentFile()) != null) {
11757                    f = parent;
11758                    parent = tmp;
11759                }
11760                codeRoot = f;
11761                Slog.w(TAG, "Unrecognized code path "
11762                        + codePath + " - using " + codeRoot);
11763            } catch (IOException e) {
11764                // Can't canonicalize the code path -- shenanigans?
11765                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11766                return Environment.getRootDirectory().getPath();
11767            }
11768        }
11769        return codeRoot.getPath();
11770    }
11771
11772    /**
11773     * Derive and set the location of native libraries for the given package,
11774     * which varies depending on where and how the package was installed.
11775     */
11776    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11777        final ApplicationInfo info = pkg.applicationInfo;
11778        final String codePath = pkg.codePath;
11779        final File codeFile = new File(codePath);
11780        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11781        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11782
11783        info.nativeLibraryRootDir = null;
11784        info.nativeLibraryRootRequiresIsa = false;
11785        info.nativeLibraryDir = null;
11786        info.secondaryNativeLibraryDir = null;
11787
11788        if (isApkFile(codeFile)) {
11789            // Monolithic install
11790            if (bundledApp) {
11791                // If "/system/lib64/apkname" exists, assume that is the per-package
11792                // native library directory to use; otherwise use "/system/lib/apkname".
11793                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11794                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11795                        getPrimaryInstructionSet(info));
11796
11797                // This is a bundled system app so choose the path based on the ABI.
11798                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11799                // is just the default path.
11800                final String apkName = deriveCodePathName(codePath);
11801                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11802                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11803                        apkName).getAbsolutePath();
11804
11805                if (info.secondaryCpuAbi != null) {
11806                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11807                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11808                            secondaryLibDir, apkName).getAbsolutePath();
11809                }
11810            } else if (asecApp) {
11811                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11812                        .getAbsolutePath();
11813            } else {
11814                final String apkName = deriveCodePathName(codePath);
11815                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11816                        .getAbsolutePath();
11817            }
11818
11819            info.nativeLibraryRootRequiresIsa = false;
11820            info.nativeLibraryDir = info.nativeLibraryRootDir;
11821        } else {
11822            // Cluster install
11823            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11824            info.nativeLibraryRootRequiresIsa = true;
11825
11826            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11827                    getPrimaryInstructionSet(info)).getAbsolutePath();
11828
11829            if (info.secondaryCpuAbi != null) {
11830                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11831                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11832            }
11833        }
11834    }
11835
11836    /**
11837     * Calculate the abis and roots for a bundled app. These can uniquely
11838     * be determined from the contents of the system partition, i.e whether
11839     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11840     * of this information, and instead assume that the system was built
11841     * sensibly.
11842     */
11843    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11844                                           PackageSetting pkgSetting) {
11845        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11846
11847        // If "/system/lib64/apkname" exists, assume that is the per-package
11848        // native library directory to use; otherwise use "/system/lib/apkname".
11849        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11850        setBundledAppAbi(pkg, apkRoot, apkName);
11851        // pkgSetting might be null during rescan following uninstall of updates
11852        // to a bundled app, so accommodate that possibility.  The settings in
11853        // that case will be established later from the parsed package.
11854        //
11855        // If the settings aren't null, sync them up with what we've just derived.
11856        // note that apkRoot isn't stored in the package settings.
11857        if (pkgSetting != null) {
11858            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11859            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11860        }
11861    }
11862
11863    /**
11864     * Deduces the ABI of a bundled app and sets the relevant fields on the
11865     * parsed pkg object.
11866     *
11867     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11868     *        under which system libraries are installed.
11869     * @param apkName the name of the installed package.
11870     */
11871    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11872        final File codeFile = new File(pkg.codePath);
11873
11874        final boolean has64BitLibs;
11875        final boolean has32BitLibs;
11876        if (isApkFile(codeFile)) {
11877            // Monolithic install
11878            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11879            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11880        } else {
11881            // Cluster install
11882            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11883            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11884                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11885                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11886                has64BitLibs = (new File(rootDir, isa)).exists();
11887            } else {
11888                has64BitLibs = false;
11889            }
11890            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11891                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11892                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11893                has32BitLibs = (new File(rootDir, isa)).exists();
11894            } else {
11895                has32BitLibs = false;
11896            }
11897        }
11898
11899        if (has64BitLibs && !has32BitLibs) {
11900            // The package has 64 bit libs, but not 32 bit libs. Its primary
11901            // ABI should be 64 bit. We can safely assume here that the bundled
11902            // native libraries correspond to the most preferred ABI in the list.
11903
11904            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11905            pkg.applicationInfo.secondaryCpuAbi = null;
11906        } else if (has32BitLibs && !has64BitLibs) {
11907            // The package has 32 bit libs but not 64 bit libs. Its primary
11908            // ABI should be 32 bit.
11909
11910            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11911            pkg.applicationInfo.secondaryCpuAbi = null;
11912        } else if (has32BitLibs && has64BitLibs) {
11913            // The application has both 64 and 32 bit bundled libraries. We check
11914            // here that the app declares multiArch support, and warn if it doesn't.
11915            //
11916            // We will be lenient here and record both ABIs. The primary will be the
11917            // ABI that's higher on the list, i.e, a device that's configured to prefer
11918            // 64 bit apps will see a 64 bit primary ABI,
11919
11920            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11921                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11922            }
11923
11924            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11925                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11926                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11927            } else {
11928                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11929                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11930            }
11931        } else {
11932            pkg.applicationInfo.primaryCpuAbi = null;
11933            pkg.applicationInfo.secondaryCpuAbi = null;
11934        }
11935    }
11936
11937    private void killApplication(String pkgName, int appId, String reason) {
11938        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11939    }
11940
11941    private void killApplication(String pkgName, int appId, int userId, String reason) {
11942        // Request the ActivityManager to kill the process(only for existing packages)
11943        // so that we do not end up in a confused state while the user is still using the older
11944        // version of the application while the new one gets installed.
11945        final long token = Binder.clearCallingIdentity();
11946        try {
11947            IActivityManager am = ActivityManager.getService();
11948            if (am != null) {
11949                try {
11950                    am.killApplication(pkgName, appId, userId, reason);
11951                } catch (RemoteException e) {
11952                }
11953            }
11954        } finally {
11955            Binder.restoreCallingIdentity(token);
11956        }
11957    }
11958
11959    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11960        // Remove the parent package setting
11961        PackageSetting ps = (PackageSetting) pkg.mExtras;
11962        if (ps != null) {
11963            removePackageLI(ps, chatty);
11964        }
11965        // Remove the child package setting
11966        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11967        for (int i = 0; i < childCount; i++) {
11968            PackageParser.Package childPkg = pkg.childPackages.get(i);
11969            ps = (PackageSetting) childPkg.mExtras;
11970            if (ps != null) {
11971                removePackageLI(ps, chatty);
11972            }
11973        }
11974    }
11975
11976    void removePackageLI(PackageSetting ps, boolean chatty) {
11977        if (DEBUG_INSTALL) {
11978            if (chatty)
11979                Log.d(TAG, "Removing package " + ps.name);
11980        }
11981
11982        // writer
11983        synchronized (mPackages) {
11984            mPackages.remove(ps.name);
11985            final PackageParser.Package pkg = ps.pkg;
11986            if (pkg != null) {
11987                cleanPackageDataStructuresLILPw(pkg, chatty);
11988            }
11989        }
11990    }
11991
11992    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11993        if (DEBUG_INSTALL) {
11994            if (chatty)
11995                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11996        }
11997
11998        // writer
11999        synchronized (mPackages) {
12000            // Remove the parent package
12001            mPackages.remove(pkg.applicationInfo.packageName);
12002            cleanPackageDataStructuresLILPw(pkg, chatty);
12003
12004            // Remove the child packages
12005            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12006            for (int i = 0; i < childCount; i++) {
12007                PackageParser.Package childPkg = pkg.childPackages.get(i);
12008                mPackages.remove(childPkg.applicationInfo.packageName);
12009                cleanPackageDataStructuresLILPw(childPkg, chatty);
12010            }
12011        }
12012    }
12013
12014    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12015        int N = pkg.providers.size();
12016        StringBuilder r = null;
12017        int i;
12018        for (i=0; i<N; i++) {
12019            PackageParser.Provider p = pkg.providers.get(i);
12020            mProviders.removeProvider(p);
12021            if (p.info.authority == null) {
12022
12023                /* There was another ContentProvider with this authority when
12024                 * this app was installed so this authority is null,
12025                 * Ignore it as we don't have to unregister the provider.
12026                 */
12027                continue;
12028            }
12029            String names[] = p.info.authority.split(";");
12030            for (int j = 0; j < names.length; j++) {
12031                if (mProvidersByAuthority.get(names[j]) == p) {
12032                    mProvidersByAuthority.remove(names[j]);
12033                    if (DEBUG_REMOVE) {
12034                        if (chatty)
12035                            Log.d(TAG, "Unregistered content provider: " + names[j]
12036                                    + ", className = " + p.info.name + ", isSyncable = "
12037                                    + p.info.isSyncable);
12038                    }
12039                }
12040            }
12041            if (DEBUG_REMOVE && chatty) {
12042                if (r == null) {
12043                    r = new StringBuilder(256);
12044                } else {
12045                    r.append(' ');
12046                }
12047                r.append(p.info.name);
12048            }
12049        }
12050        if (r != null) {
12051            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12052        }
12053
12054        N = pkg.services.size();
12055        r = null;
12056        for (i=0; i<N; i++) {
12057            PackageParser.Service s = pkg.services.get(i);
12058            mServices.removeService(s);
12059            if (chatty) {
12060                if (r == null) {
12061                    r = new StringBuilder(256);
12062                } else {
12063                    r.append(' ');
12064                }
12065                r.append(s.info.name);
12066            }
12067        }
12068        if (r != null) {
12069            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12070        }
12071
12072        N = pkg.receivers.size();
12073        r = null;
12074        for (i=0; i<N; i++) {
12075            PackageParser.Activity a = pkg.receivers.get(i);
12076            mReceivers.removeActivity(a, "receiver");
12077            if (DEBUG_REMOVE && chatty) {
12078                if (r == null) {
12079                    r = new StringBuilder(256);
12080                } else {
12081                    r.append(' ');
12082                }
12083                r.append(a.info.name);
12084            }
12085        }
12086        if (r != null) {
12087            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12088        }
12089
12090        N = pkg.activities.size();
12091        r = null;
12092        for (i=0; i<N; i++) {
12093            PackageParser.Activity a = pkg.activities.get(i);
12094            mActivities.removeActivity(a, "activity");
12095            if (DEBUG_REMOVE && chatty) {
12096                if (r == null) {
12097                    r = new StringBuilder(256);
12098                } else {
12099                    r.append(' ');
12100                }
12101                r.append(a.info.name);
12102            }
12103        }
12104        if (r != null) {
12105            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12106        }
12107
12108        mPermissionManager.removeAllPermissions(pkg, chatty);
12109
12110        N = pkg.instrumentation.size();
12111        r = null;
12112        for (i=0; i<N; i++) {
12113            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12114            mInstrumentation.remove(a.getComponentName());
12115            if (DEBUG_REMOVE && chatty) {
12116                if (r == null) {
12117                    r = new StringBuilder(256);
12118                } else {
12119                    r.append(' ');
12120                }
12121                r.append(a.info.name);
12122            }
12123        }
12124        if (r != null) {
12125            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12126        }
12127
12128        r = null;
12129        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12130            // Only system apps can hold shared libraries.
12131            if (pkg.libraryNames != null) {
12132                for (i = 0; i < pkg.libraryNames.size(); i++) {
12133                    String name = pkg.libraryNames.get(i);
12134                    if (removeSharedLibraryLPw(name, 0)) {
12135                        if (DEBUG_REMOVE && chatty) {
12136                            if (r == null) {
12137                                r = new StringBuilder(256);
12138                            } else {
12139                                r.append(' ');
12140                            }
12141                            r.append(name);
12142                        }
12143                    }
12144                }
12145            }
12146        }
12147
12148        r = null;
12149
12150        // Any package can hold static shared libraries.
12151        if (pkg.staticSharedLibName != null) {
12152            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12153                if (DEBUG_REMOVE && chatty) {
12154                    if (r == null) {
12155                        r = new StringBuilder(256);
12156                    } else {
12157                        r.append(' ');
12158                    }
12159                    r.append(pkg.staticSharedLibName);
12160                }
12161            }
12162        }
12163
12164        if (r != null) {
12165            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12166        }
12167    }
12168
12169
12170    final class ActivityIntentResolver
12171            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12172        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12173                boolean defaultOnly, int userId) {
12174            if (!sUserManager.exists(userId)) return null;
12175            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12176            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12177        }
12178
12179        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12180                int userId) {
12181            if (!sUserManager.exists(userId)) return null;
12182            mFlags = flags;
12183            return super.queryIntent(intent, resolvedType,
12184                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12185                    userId);
12186        }
12187
12188        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12189                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12190            if (!sUserManager.exists(userId)) return null;
12191            if (packageActivities == null) {
12192                return null;
12193            }
12194            mFlags = flags;
12195            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12196            final int N = packageActivities.size();
12197            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12198                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12199
12200            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12201            for (int i = 0; i < N; ++i) {
12202                intentFilters = packageActivities.get(i).intents;
12203                if (intentFilters != null && intentFilters.size() > 0) {
12204                    PackageParser.ActivityIntentInfo[] array =
12205                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12206                    intentFilters.toArray(array);
12207                    listCut.add(array);
12208                }
12209            }
12210            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12211        }
12212
12213        /**
12214         * Finds a privileged activity that matches the specified activity names.
12215         */
12216        private PackageParser.Activity findMatchingActivity(
12217                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12218            for (PackageParser.Activity sysActivity : activityList) {
12219                if (sysActivity.info.name.equals(activityInfo.name)) {
12220                    return sysActivity;
12221                }
12222                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12223                    return sysActivity;
12224                }
12225                if (sysActivity.info.targetActivity != null) {
12226                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12227                        return sysActivity;
12228                    }
12229                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12230                        return sysActivity;
12231                    }
12232                }
12233            }
12234            return null;
12235        }
12236
12237        public class IterGenerator<E> {
12238            public Iterator<E> generate(ActivityIntentInfo info) {
12239                return null;
12240            }
12241        }
12242
12243        public class ActionIterGenerator extends IterGenerator<String> {
12244            @Override
12245            public Iterator<String> generate(ActivityIntentInfo info) {
12246                return info.actionsIterator();
12247            }
12248        }
12249
12250        public class CategoriesIterGenerator extends IterGenerator<String> {
12251            @Override
12252            public Iterator<String> generate(ActivityIntentInfo info) {
12253                return info.categoriesIterator();
12254            }
12255        }
12256
12257        public class SchemesIterGenerator extends IterGenerator<String> {
12258            @Override
12259            public Iterator<String> generate(ActivityIntentInfo info) {
12260                return info.schemesIterator();
12261            }
12262        }
12263
12264        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12265            @Override
12266            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12267                return info.authoritiesIterator();
12268            }
12269        }
12270
12271        /**
12272         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12273         * MODIFIED. Do not pass in a list that should not be changed.
12274         */
12275        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12276                IterGenerator<T> generator, Iterator<T> searchIterator) {
12277            // loop through the set of actions; every one must be found in the intent filter
12278            while (searchIterator.hasNext()) {
12279                // we must have at least one filter in the list to consider a match
12280                if (intentList.size() == 0) {
12281                    break;
12282                }
12283
12284                final T searchAction = searchIterator.next();
12285
12286                // loop through the set of intent filters
12287                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12288                while (intentIter.hasNext()) {
12289                    final ActivityIntentInfo intentInfo = intentIter.next();
12290                    boolean selectionFound = false;
12291
12292                    // loop through the intent filter's selection criteria; at least one
12293                    // of them must match the searched criteria
12294                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12295                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12296                        final T intentSelection = intentSelectionIter.next();
12297                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12298                            selectionFound = true;
12299                            break;
12300                        }
12301                    }
12302
12303                    // the selection criteria wasn't found in this filter's set; this filter
12304                    // is not a potential match
12305                    if (!selectionFound) {
12306                        intentIter.remove();
12307                    }
12308                }
12309            }
12310        }
12311
12312        private boolean isProtectedAction(ActivityIntentInfo filter) {
12313            final Iterator<String> actionsIter = filter.actionsIterator();
12314            while (actionsIter != null && actionsIter.hasNext()) {
12315                final String filterAction = actionsIter.next();
12316                if (PROTECTED_ACTIONS.contains(filterAction)) {
12317                    return true;
12318                }
12319            }
12320            return false;
12321        }
12322
12323        /**
12324         * Adjusts the priority of the given intent filter according to policy.
12325         * <p>
12326         * <ul>
12327         * <li>The priority for non privileged applications is capped to '0'</li>
12328         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12329         * <li>The priority for unbundled updates to privileged applications is capped to the
12330         *      priority defined on the system partition</li>
12331         * </ul>
12332         * <p>
12333         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12334         * allowed to obtain any priority on any action.
12335         */
12336        private void adjustPriority(
12337                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12338            // nothing to do; priority is fine as-is
12339            if (intent.getPriority() <= 0) {
12340                return;
12341            }
12342
12343            final ActivityInfo activityInfo = intent.activity.info;
12344            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12345
12346            final boolean privilegedApp =
12347                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12348            if (!privilegedApp) {
12349                // non-privileged applications can never define a priority >0
12350                if (DEBUG_FILTERS) {
12351                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12352                            + " package: " + applicationInfo.packageName
12353                            + " activity: " + intent.activity.className
12354                            + " origPrio: " + intent.getPriority());
12355                }
12356                intent.setPriority(0);
12357                return;
12358            }
12359
12360            if (systemActivities == null) {
12361                // the system package is not disabled; we're parsing the system partition
12362                if (isProtectedAction(intent)) {
12363                    if (mDeferProtectedFilters) {
12364                        // We can't deal with these just yet. No component should ever obtain a
12365                        // >0 priority for a protected actions, with ONE exception -- the setup
12366                        // wizard. The setup wizard, however, cannot be known until we're able to
12367                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12368                        // until all intent filters have been processed. Chicken, meet egg.
12369                        // Let the filter temporarily have a high priority and rectify the
12370                        // priorities after all system packages have been scanned.
12371                        mProtectedFilters.add(intent);
12372                        if (DEBUG_FILTERS) {
12373                            Slog.i(TAG, "Protected action; save for later;"
12374                                    + " package: " + applicationInfo.packageName
12375                                    + " activity: " + intent.activity.className
12376                                    + " origPrio: " + intent.getPriority());
12377                        }
12378                        return;
12379                    } else {
12380                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12381                            Slog.i(TAG, "No setup wizard;"
12382                                + " All protected intents capped to priority 0");
12383                        }
12384                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12385                            if (DEBUG_FILTERS) {
12386                                Slog.i(TAG, "Found setup wizard;"
12387                                    + " allow priority " + intent.getPriority() + ";"
12388                                    + " package: " + intent.activity.info.packageName
12389                                    + " activity: " + intent.activity.className
12390                                    + " priority: " + intent.getPriority());
12391                            }
12392                            // setup wizard gets whatever it wants
12393                            return;
12394                        }
12395                        if (DEBUG_FILTERS) {
12396                            Slog.i(TAG, "Protected action; cap priority to 0;"
12397                                    + " package: " + intent.activity.info.packageName
12398                                    + " activity: " + intent.activity.className
12399                                    + " origPrio: " + intent.getPriority());
12400                        }
12401                        intent.setPriority(0);
12402                        return;
12403                    }
12404                }
12405                // privileged apps on the system image get whatever priority they request
12406                return;
12407            }
12408
12409            // privileged app unbundled update ... try to find the same activity
12410            final PackageParser.Activity foundActivity =
12411                    findMatchingActivity(systemActivities, activityInfo);
12412            if (foundActivity == null) {
12413                // this is a new activity; it cannot obtain >0 priority
12414                if (DEBUG_FILTERS) {
12415                    Slog.i(TAG, "New activity; cap priority to 0;"
12416                            + " package: " + applicationInfo.packageName
12417                            + " activity: " + intent.activity.className
12418                            + " origPrio: " + intent.getPriority());
12419                }
12420                intent.setPriority(0);
12421                return;
12422            }
12423
12424            // found activity, now check for filter equivalence
12425
12426            // a shallow copy is enough; we modify the list, not its contents
12427            final List<ActivityIntentInfo> intentListCopy =
12428                    new ArrayList<>(foundActivity.intents);
12429            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12430
12431            // find matching action subsets
12432            final Iterator<String> actionsIterator = intent.actionsIterator();
12433            if (actionsIterator != null) {
12434                getIntentListSubset(
12435                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12436                if (intentListCopy.size() == 0) {
12437                    // no more intents to match; we're not equivalent
12438                    if (DEBUG_FILTERS) {
12439                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12440                                + " package: " + applicationInfo.packageName
12441                                + " activity: " + intent.activity.className
12442                                + " origPrio: " + intent.getPriority());
12443                    }
12444                    intent.setPriority(0);
12445                    return;
12446                }
12447            }
12448
12449            // find matching category subsets
12450            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12451            if (categoriesIterator != null) {
12452                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12453                        categoriesIterator);
12454                if (intentListCopy.size() == 0) {
12455                    // no more intents to match; we're not equivalent
12456                    if (DEBUG_FILTERS) {
12457                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12458                                + " package: " + applicationInfo.packageName
12459                                + " activity: " + intent.activity.className
12460                                + " origPrio: " + intent.getPriority());
12461                    }
12462                    intent.setPriority(0);
12463                    return;
12464                }
12465            }
12466
12467            // find matching schemes subsets
12468            final Iterator<String> schemesIterator = intent.schemesIterator();
12469            if (schemesIterator != null) {
12470                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12471                        schemesIterator);
12472                if (intentListCopy.size() == 0) {
12473                    // no more intents to match; we're not equivalent
12474                    if (DEBUG_FILTERS) {
12475                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12476                                + " package: " + applicationInfo.packageName
12477                                + " activity: " + intent.activity.className
12478                                + " origPrio: " + intent.getPriority());
12479                    }
12480                    intent.setPriority(0);
12481                    return;
12482                }
12483            }
12484
12485            // find matching authorities subsets
12486            final Iterator<IntentFilter.AuthorityEntry>
12487                    authoritiesIterator = intent.authoritiesIterator();
12488            if (authoritiesIterator != null) {
12489                getIntentListSubset(intentListCopy,
12490                        new AuthoritiesIterGenerator(),
12491                        authoritiesIterator);
12492                if (intentListCopy.size() == 0) {
12493                    // no more intents to match; we're not equivalent
12494                    if (DEBUG_FILTERS) {
12495                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12496                                + " package: " + applicationInfo.packageName
12497                                + " activity: " + intent.activity.className
12498                                + " origPrio: " + intent.getPriority());
12499                    }
12500                    intent.setPriority(0);
12501                    return;
12502                }
12503            }
12504
12505            // we found matching filter(s); app gets the max priority of all intents
12506            int cappedPriority = 0;
12507            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12508                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12509            }
12510            if (intent.getPriority() > cappedPriority) {
12511                if (DEBUG_FILTERS) {
12512                    Slog.i(TAG, "Found matching filter(s);"
12513                            + " cap priority to " + cappedPriority + ";"
12514                            + " package: " + applicationInfo.packageName
12515                            + " activity: " + intent.activity.className
12516                            + " origPrio: " + intent.getPriority());
12517                }
12518                intent.setPriority(cappedPriority);
12519                return;
12520            }
12521            // all this for nothing; the requested priority was <= what was on the system
12522        }
12523
12524        public final void addActivity(PackageParser.Activity a, String type) {
12525            mActivities.put(a.getComponentName(), a);
12526            if (DEBUG_SHOW_INFO)
12527                Log.v(
12528                TAG, "  " + type + " " +
12529                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12530            if (DEBUG_SHOW_INFO)
12531                Log.v(TAG, "    Class=" + a.info.name);
12532            final int NI = a.intents.size();
12533            for (int j=0; j<NI; j++) {
12534                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12535                if ("activity".equals(type)) {
12536                    final PackageSetting ps =
12537                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12538                    final List<PackageParser.Activity> systemActivities =
12539                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12540                    adjustPriority(systemActivities, intent);
12541                }
12542                if (DEBUG_SHOW_INFO) {
12543                    Log.v(TAG, "    IntentFilter:");
12544                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12545                }
12546                if (!intent.debugCheck()) {
12547                    Log.w(TAG, "==> For Activity " + a.info.name);
12548                }
12549                addFilter(intent);
12550            }
12551        }
12552
12553        public final void removeActivity(PackageParser.Activity a, String type) {
12554            mActivities.remove(a.getComponentName());
12555            if (DEBUG_SHOW_INFO) {
12556                Log.v(TAG, "  " + type + " "
12557                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12558                                : a.info.name) + ":");
12559                Log.v(TAG, "    Class=" + a.info.name);
12560            }
12561            final int NI = a.intents.size();
12562            for (int j=0; j<NI; j++) {
12563                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12564                if (DEBUG_SHOW_INFO) {
12565                    Log.v(TAG, "    IntentFilter:");
12566                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12567                }
12568                removeFilter(intent);
12569            }
12570        }
12571
12572        @Override
12573        protected boolean allowFilterResult(
12574                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12575            ActivityInfo filterAi = filter.activity.info;
12576            for (int i=dest.size()-1; i>=0; i--) {
12577                ActivityInfo destAi = dest.get(i).activityInfo;
12578                if (destAi.name == filterAi.name
12579                        && destAi.packageName == filterAi.packageName) {
12580                    return false;
12581                }
12582            }
12583            return true;
12584        }
12585
12586        @Override
12587        protected ActivityIntentInfo[] newArray(int size) {
12588            return new ActivityIntentInfo[size];
12589        }
12590
12591        @Override
12592        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12593            if (!sUserManager.exists(userId)) return true;
12594            PackageParser.Package p = filter.activity.owner;
12595            if (p != null) {
12596                PackageSetting ps = (PackageSetting)p.mExtras;
12597                if (ps != null) {
12598                    // System apps are never considered stopped for purposes of
12599                    // filtering, because there may be no way for the user to
12600                    // actually re-launch them.
12601                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12602                            && ps.getStopped(userId);
12603                }
12604            }
12605            return false;
12606        }
12607
12608        @Override
12609        protected boolean isPackageForFilter(String packageName,
12610                PackageParser.ActivityIntentInfo info) {
12611            return packageName.equals(info.activity.owner.packageName);
12612        }
12613
12614        @Override
12615        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12616                int match, int userId) {
12617            if (!sUserManager.exists(userId)) return null;
12618            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12619                return null;
12620            }
12621            final PackageParser.Activity activity = info.activity;
12622            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12623            if (ps == null) {
12624                return null;
12625            }
12626            final PackageUserState userState = ps.readUserState(userId);
12627            ActivityInfo ai =
12628                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12629            if (ai == null) {
12630                return null;
12631            }
12632            final boolean matchExplicitlyVisibleOnly =
12633                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12634            final boolean matchVisibleToInstantApp =
12635                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12636            final boolean componentVisible =
12637                    matchVisibleToInstantApp
12638                    && info.isVisibleToInstantApp()
12639                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12640            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12641            // throw out filters that aren't visible to ephemeral apps
12642            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12643                return null;
12644            }
12645            // throw out instant app filters if we're not explicitly requesting them
12646            if (!matchInstantApp && userState.instantApp) {
12647                return null;
12648            }
12649            // throw out instant app filters if updates are available; will trigger
12650            // instant app resolution
12651            if (userState.instantApp && ps.isUpdateAvailable()) {
12652                return null;
12653            }
12654            final ResolveInfo res = new ResolveInfo();
12655            res.activityInfo = ai;
12656            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12657                res.filter = info;
12658            }
12659            if (info != null) {
12660                res.handleAllWebDataURI = info.handleAllWebDataURI();
12661            }
12662            res.priority = info.getPriority();
12663            res.preferredOrder = activity.owner.mPreferredOrder;
12664            //System.out.println("Result: " + res.activityInfo.className +
12665            //                   " = " + res.priority);
12666            res.match = match;
12667            res.isDefault = info.hasDefault;
12668            res.labelRes = info.labelRes;
12669            res.nonLocalizedLabel = info.nonLocalizedLabel;
12670            if (userNeedsBadging(userId)) {
12671                res.noResourceId = true;
12672            } else {
12673                res.icon = info.icon;
12674            }
12675            res.iconResourceId = info.icon;
12676            res.system = res.activityInfo.applicationInfo.isSystemApp();
12677            res.isInstantAppAvailable = userState.instantApp;
12678            return res;
12679        }
12680
12681        @Override
12682        protected void sortResults(List<ResolveInfo> results) {
12683            Collections.sort(results, mResolvePrioritySorter);
12684        }
12685
12686        @Override
12687        protected void dumpFilter(PrintWriter out, String prefix,
12688                PackageParser.ActivityIntentInfo filter) {
12689            out.print(prefix); out.print(
12690                    Integer.toHexString(System.identityHashCode(filter.activity)));
12691                    out.print(' ');
12692                    filter.activity.printComponentShortName(out);
12693                    out.print(" filter ");
12694                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12695        }
12696
12697        @Override
12698        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12699            return filter.activity;
12700        }
12701
12702        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12703            PackageParser.Activity activity = (PackageParser.Activity)label;
12704            out.print(prefix); out.print(
12705                    Integer.toHexString(System.identityHashCode(activity)));
12706                    out.print(' ');
12707                    activity.printComponentShortName(out);
12708            if (count > 1) {
12709                out.print(" ("); out.print(count); out.print(" filters)");
12710            }
12711            out.println();
12712        }
12713
12714        // Keys are String (activity class name), values are Activity.
12715        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12716                = new ArrayMap<ComponentName, PackageParser.Activity>();
12717        private int mFlags;
12718    }
12719
12720    private final class ServiceIntentResolver
12721            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12722        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12723                boolean defaultOnly, int userId) {
12724            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12725            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12726        }
12727
12728        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12729                int userId) {
12730            if (!sUserManager.exists(userId)) return null;
12731            mFlags = flags;
12732            return super.queryIntent(intent, resolvedType,
12733                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12734                    userId);
12735        }
12736
12737        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12738                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12739            if (!sUserManager.exists(userId)) return null;
12740            if (packageServices == null) {
12741                return null;
12742            }
12743            mFlags = flags;
12744            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12745            final int N = packageServices.size();
12746            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12747                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12748
12749            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12750            for (int i = 0; i < N; ++i) {
12751                intentFilters = packageServices.get(i).intents;
12752                if (intentFilters != null && intentFilters.size() > 0) {
12753                    PackageParser.ServiceIntentInfo[] array =
12754                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12755                    intentFilters.toArray(array);
12756                    listCut.add(array);
12757                }
12758            }
12759            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12760        }
12761
12762        public final void addService(PackageParser.Service s) {
12763            mServices.put(s.getComponentName(), s);
12764            if (DEBUG_SHOW_INFO) {
12765                Log.v(TAG, "  "
12766                        + (s.info.nonLocalizedLabel != null
12767                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12768                Log.v(TAG, "    Class=" + s.info.name);
12769            }
12770            final int NI = s.intents.size();
12771            int j;
12772            for (j=0; j<NI; j++) {
12773                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12774                if (DEBUG_SHOW_INFO) {
12775                    Log.v(TAG, "    IntentFilter:");
12776                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12777                }
12778                if (!intent.debugCheck()) {
12779                    Log.w(TAG, "==> For Service " + s.info.name);
12780                }
12781                addFilter(intent);
12782            }
12783        }
12784
12785        public final void removeService(PackageParser.Service s) {
12786            mServices.remove(s.getComponentName());
12787            if (DEBUG_SHOW_INFO) {
12788                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12789                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12790                Log.v(TAG, "    Class=" + s.info.name);
12791            }
12792            final int NI = s.intents.size();
12793            int j;
12794            for (j=0; j<NI; j++) {
12795                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12796                if (DEBUG_SHOW_INFO) {
12797                    Log.v(TAG, "    IntentFilter:");
12798                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12799                }
12800                removeFilter(intent);
12801            }
12802        }
12803
12804        @Override
12805        protected boolean allowFilterResult(
12806                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12807            ServiceInfo filterSi = filter.service.info;
12808            for (int i=dest.size()-1; i>=0; i--) {
12809                ServiceInfo destAi = dest.get(i).serviceInfo;
12810                if (destAi.name == filterSi.name
12811                        && destAi.packageName == filterSi.packageName) {
12812                    return false;
12813                }
12814            }
12815            return true;
12816        }
12817
12818        @Override
12819        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12820            return new PackageParser.ServiceIntentInfo[size];
12821        }
12822
12823        @Override
12824        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12825            if (!sUserManager.exists(userId)) return true;
12826            PackageParser.Package p = filter.service.owner;
12827            if (p != null) {
12828                PackageSetting ps = (PackageSetting)p.mExtras;
12829                if (ps != null) {
12830                    // System apps are never considered stopped for purposes of
12831                    // filtering, because there may be no way for the user to
12832                    // actually re-launch them.
12833                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12834                            && ps.getStopped(userId);
12835                }
12836            }
12837            return false;
12838        }
12839
12840        @Override
12841        protected boolean isPackageForFilter(String packageName,
12842                PackageParser.ServiceIntentInfo info) {
12843            return packageName.equals(info.service.owner.packageName);
12844        }
12845
12846        @Override
12847        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12848                int match, int userId) {
12849            if (!sUserManager.exists(userId)) return null;
12850            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12851            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12852                return null;
12853            }
12854            final PackageParser.Service service = info.service;
12855            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12856            if (ps == null) {
12857                return null;
12858            }
12859            final PackageUserState userState = ps.readUserState(userId);
12860            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12861                    userState, userId);
12862            if (si == null) {
12863                return null;
12864            }
12865            final boolean matchVisibleToInstantApp =
12866                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12867            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12868            // throw out filters that aren't visible to ephemeral apps
12869            if (matchVisibleToInstantApp
12870                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12871                return null;
12872            }
12873            // throw out ephemeral filters if we're not explicitly requesting them
12874            if (!isInstantApp && userState.instantApp) {
12875                return null;
12876            }
12877            // throw out instant app filters if updates are available; will trigger
12878            // instant app resolution
12879            if (userState.instantApp && ps.isUpdateAvailable()) {
12880                return null;
12881            }
12882            final ResolveInfo res = new ResolveInfo();
12883            res.serviceInfo = si;
12884            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12885                res.filter = filter;
12886            }
12887            res.priority = info.getPriority();
12888            res.preferredOrder = service.owner.mPreferredOrder;
12889            res.match = match;
12890            res.isDefault = info.hasDefault;
12891            res.labelRes = info.labelRes;
12892            res.nonLocalizedLabel = info.nonLocalizedLabel;
12893            res.icon = info.icon;
12894            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12895            return res;
12896        }
12897
12898        @Override
12899        protected void sortResults(List<ResolveInfo> results) {
12900            Collections.sort(results, mResolvePrioritySorter);
12901        }
12902
12903        @Override
12904        protected void dumpFilter(PrintWriter out, String prefix,
12905                PackageParser.ServiceIntentInfo filter) {
12906            out.print(prefix); out.print(
12907                    Integer.toHexString(System.identityHashCode(filter.service)));
12908                    out.print(' ');
12909                    filter.service.printComponentShortName(out);
12910                    out.print(" filter ");
12911                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12912                    if (filter.service.info.permission != null) {
12913                        out.print(" permission "); out.println(filter.service.info.permission);
12914                    } else {
12915                        out.println();
12916                    }
12917        }
12918
12919        @Override
12920        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12921            return filter.service;
12922        }
12923
12924        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12925            PackageParser.Service service = (PackageParser.Service)label;
12926            out.print(prefix); out.print(
12927                    Integer.toHexString(System.identityHashCode(service)));
12928                    out.print(' ');
12929                    service.printComponentShortName(out);
12930            if (count > 1) {
12931                out.print(" ("); out.print(count); out.print(" filters)");
12932            }
12933            out.println();
12934        }
12935
12936//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12937//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12938//            final List<ResolveInfo> retList = Lists.newArrayList();
12939//            while (i.hasNext()) {
12940//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12941//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12942//                    retList.add(resolveInfo);
12943//                }
12944//            }
12945//            return retList;
12946//        }
12947
12948        // Keys are String (activity class name), values are Activity.
12949        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12950                = new ArrayMap<ComponentName, PackageParser.Service>();
12951        private int mFlags;
12952    }
12953
12954    private final class ProviderIntentResolver
12955            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12956        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12957                boolean defaultOnly, int userId) {
12958            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12959            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12960        }
12961
12962        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12963                int userId) {
12964            if (!sUserManager.exists(userId))
12965                return null;
12966            mFlags = flags;
12967            return super.queryIntent(intent, resolvedType,
12968                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12969                    userId);
12970        }
12971
12972        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12973                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12974            if (!sUserManager.exists(userId))
12975                return null;
12976            if (packageProviders == null) {
12977                return null;
12978            }
12979            mFlags = flags;
12980            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12981            final int N = packageProviders.size();
12982            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12983                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12984
12985            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12986            for (int i = 0; i < N; ++i) {
12987                intentFilters = packageProviders.get(i).intents;
12988                if (intentFilters != null && intentFilters.size() > 0) {
12989                    PackageParser.ProviderIntentInfo[] array =
12990                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12991                    intentFilters.toArray(array);
12992                    listCut.add(array);
12993                }
12994            }
12995            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12996        }
12997
12998        public final void addProvider(PackageParser.Provider p) {
12999            if (mProviders.containsKey(p.getComponentName())) {
13000                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13001                return;
13002            }
13003
13004            mProviders.put(p.getComponentName(), p);
13005            if (DEBUG_SHOW_INFO) {
13006                Log.v(TAG, "  "
13007                        + (p.info.nonLocalizedLabel != null
13008                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13009                Log.v(TAG, "    Class=" + p.info.name);
13010            }
13011            final int NI = p.intents.size();
13012            int j;
13013            for (j = 0; j < NI; j++) {
13014                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13015                if (DEBUG_SHOW_INFO) {
13016                    Log.v(TAG, "    IntentFilter:");
13017                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13018                }
13019                if (!intent.debugCheck()) {
13020                    Log.w(TAG, "==> For Provider " + p.info.name);
13021                }
13022                addFilter(intent);
13023            }
13024        }
13025
13026        public final void removeProvider(PackageParser.Provider p) {
13027            mProviders.remove(p.getComponentName());
13028            if (DEBUG_SHOW_INFO) {
13029                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13030                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13031                Log.v(TAG, "    Class=" + p.info.name);
13032            }
13033            final int NI = p.intents.size();
13034            int j;
13035            for (j = 0; j < NI; j++) {
13036                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13037                if (DEBUG_SHOW_INFO) {
13038                    Log.v(TAG, "    IntentFilter:");
13039                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13040                }
13041                removeFilter(intent);
13042            }
13043        }
13044
13045        @Override
13046        protected boolean allowFilterResult(
13047                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13048            ProviderInfo filterPi = filter.provider.info;
13049            for (int i = dest.size() - 1; i >= 0; i--) {
13050                ProviderInfo destPi = dest.get(i).providerInfo;
13051                if (destPi.name == filterPi.name
13052                        && destPi.packageName == filterPi.packageName) {
13053                    return false;
13054                }
13055            }
13056            return true;
13057        }
13058
13059        @Override
13060        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13061            return new PackageParser.ProviderIntentInfo[size];
13062        }
13063
13064        @Override
13065        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13066            if (!sUserManager.exists(userId))
13067                return true;
13068            PackageParser.Package p = filter.provider.owner;
13069            if (p != null) {
13070                PackageSetting ps = (PackageSetting) p.mExtras;
13071                if (ps != null) {
13072                    // System apps are never considered stopped for purposes of
13073                    // filtering, because there may be no way for the user to
13074                    // actually re-launch them.
13075                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13076                            && ps.getStopped(userId);
13077                }
13078            }
13079            return false;
13080        }
13081
13082        @Override
13083        protected boolean isPackageForFilter(String packageName,
13084                PackageParser.ProviderIntentInfo info) {
13085            return packageName.equals(info.provider.owner.packageName);
13086        }
13087
13088        @Override
13089        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13090                int match, int userId) {
13091            if (!sUserManager.exists(userId))
13092                return null;
13093            final PackageParser.ProviderIntentInfo info = filter;
13094            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13095                return null;
13096            }
13097            final PackageParser.Provider provider = info.provider;
13098            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13099            if (ps == null) {
13100                return null;
13101            }
13102            final PackageUserState userState = ps.readUserState(userId);
13103            final boolean matchVisibleToInstantApp =
13104                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13105            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13106            // throw out filters that aren't visible to instant applications
13107            if (matchVisibleToInstantApp
13108                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13109                return null;
13110            }
13111            // throw out instant application filters if we're not explicitly requesting them
13112            if (!isInstantApp && userState.instantApp) {
13113                return null;
13114            }
13115            // throw out instant application filters if updates are available; will trigger
13116            // instant application resolution
13117            if (userState.instantApp && ps.isUpdateAvailable()) {
13118                return null;
13119            }
13120            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13121                    userState, userId);
13122            if (pi == null) {
13123                return null;
13124            }
13125            final ResolveInfo res = new ResolveInfo();
13126            res.providerInfo = pi;
13127            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13128                res.filter = filter;
13129            }
13130            res.priority = info.getPriority();
13131            res.preferredOrder = provider.owner.mPreferredOrder;
13132            res.match = match;
13133            res.isDefault = info.hasDefault;
13134            res.labelRes = info.labelRes;
13135            res.nonLocalizedLabel = info.nonLocalizedLabel;
13136            res.icon = info.icon;
13137            res.system = res.providerInfo.applicationInfo.isSystemApp();
13138            return res;
13139        }
13140
13141        @Override
13142        protected void sortResults(List<ResolveInfo> results) {
13143            Collections.sort(results, mResolvePrioritySorter);
13144        }
13145
13146        @Override
13147        protected void dumpFilter(PrintWriter out, String prefix,
13148                PackageParser.ProviderIntentInfo filter) {
13149            out.print(prefix);
13150            out.print(
13151                    Integer.toHexString(System.identityHashCode(filter.provider)));
13152            out.print(' ');
13153            filter.provider.printComponentShortName(out);
13154            out.print(" filter ");
13155            out.println(Integer.toHexString(System.identityHashCode(filter)));
13156        }
13157
13158        @Override
13159        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13160            return filter.provider;
13161        }
13162
13163        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13164            PackageParser.Provider provider = (PackageParser.Provider)label;
13165            out.print(prefix); out.print(
13166                    Integer.toHexString(System.identityHashCode(provider)));
13167                    out.print(' ');
13168                    provider.printComponentShortName(out);
13169            if (count > 1) {
13170                out.print(" ("); out.print(count); out.print(" filters)");
13171            }
13172            out.println();
13173        }
13174
13175        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13176                = new ArrayMap<ComponentName, PackageParser.Provider>();
13177        private int mFlags;
13178    }
13179
13180    static final class InstantAppIntentResolver
13181            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13182            AuxiliaryResolveInfo.AuxiliaryFilter> {
13183        /**
13184         * The result that has the highest defined order. Ordering applies on a
13185         * per-package basis. Mapping is from package name to Pair of order and
13186         * EphemeralResolveInfo.
13187         * <p>
13188         * NOTE: This is implemented as a field variable for convenience and efficiency.
13189         * By having a field variable, we're able to track filter ordering as soon as
13190         * a non-zero order is defined. Otherwise, multiple loops across the result set
13191         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13192         * this needs to be contained entirely within {@link #filterResults}.
13193         */
13194        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13195
13196        @Override
13197        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13198            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13199        }
13200
13201        @Override
13202        protected boolean isPackageForFilter(String packageName,
13203                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13204            return true;
13205        }
13206
13207        @Override
13208        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13209                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13210            if (!sUserManager.exists(userId)) {
13211                return null;
13212            }
13213            final String packageName = responseObj.resolveInfo.getPackageName();
13214            final Integer order = responseObj.getOrder();
13215            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13216                    mOrderResult.get(packageName);
13217            // ordering is enabled and this item's order isn't high enough
13218            if (lastOrderResult != null && lastOrderResult.first >= order) {
13219                return null;
13220            }
13221            final InstantAppResolveInfo res = responseObj.resolveInfo;
13222            if (order > 0) {
13223                // non-zero order, enable ordering
13224                mOrderResult.put(packageName, new Pair<>(order, res));
13225            }
13226            return responseObj;
13227        }
13228
13229        @Override
13230        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13231            // only do work if ordering is enabled [most of the time it won't be]
13232            if (mOrderResult.size() == 0) {
13233                return;
13234            }
13235            int resultSize = results.size();
13236            for (int i = 0; i < resultSize; i++) {
13237                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13238                final String packageName = info.getPackageName();
13239                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13240                if (savedInfo == null) {
13241                    // package doesn't having ordering
13242                    continue;
13243                }
13244                if (savedInfo.second == info) {
13245                    // circled back to the highest ordered item; remove from order list
13246                    mOrderResult.remove(packageName);
13247                    if (mOrderResult.size() == 0) {
13248                        // no more ordered items
13249                        break;
13250                    }
13251                    continue;
13252                }
13253                // item has a worse order, remove it from the result list
13254                results.remove(i);
13255                resultSize--;
13256                i--;
13257            }
13258        }
13259    }
13260
13261    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13262            new Comparator<ResolveInfo>() {
13263        public int compare(ResolveInfo r1, ResolveInfo r2) {
13264            int v1 = r1.priority;
13265            int v2 = r2.priority;
13266            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13267            if (v1 != v2) {
13268                return (v1 > v2) ? -1 : 1;
13269            }
13270            v1 = r1.preferredOrder;
13271            v2 = r2.preferredOrder;
13272            if (v1 != v2) {
13273                return (v1 > v2) ? -1 : 1;
13274            }
13275            if (r1.isDefault != r2.isDefault) {
13276                return r1.isDefault ? -1 : 1;
13277            }
13278            v1 = r1.match;
13279            v2 = r2.match;
13280            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13281            if (v1 != v2) {
13282                return (v1 > v2) ? -1 : 1;
13283            }
13284            if (r1.system != r2.system) {
13285                return r1.system ? -1 : 1;
13286            }
13287            if (r1.activityInfo != null) {
13288                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13289            }
13290            if (r1.serviceInfo != null) {
13291                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13292            }
13293            if (r1.providerInfo != null) {
13294                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13295            }
13296            return 0;
13297        }
13298    };
13299
13300    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13301            new Comparator<ProviderInfo>() {
13302        public int compare(ProviderInfo p1, ProviderInfo p2) {
13303            final int v1 = p1.initOrder;
13304            final int v2 = p2.initOrder;
13305            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13306        }
13307    };
13308
13309    @Override
13310    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13311            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13312            final int[] userIds, int[] instantUserIds) {
13313        mHandler.post(new Runnable() {
13314            @Override
13315            public void run() {
13316                try {
13317                    final IActivityManager am = ActivityManager.getService();
13318                    if (am == null) return;
13319                    final int[] resolvedUserIds;
13320                    if (userIds == null) {
13321                        resolvedUserIds = am.getRunningUserIds();
13322                    } else {
13323                        resolvedUserIds = userIds;
13324                    }
13325                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13326                            resolvedUserIds, false);
13327                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13328                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13329                                instantUserIds, true);
13330                    }
13331                } catch (RemoteException ex) {
13332                }
13333            }
13334        });
13335    }
13336
13337    @Override
13338    public void notifyPackageAdded(String packageName) {
13339        final PackageListObserver[] observers;
13340        synchronized (mPackages) {
13341            if (mPackageListObservers.size() == 0) {
13342                return;
13343            }
13344            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13345        }
13346        for (int i = observers.length - 1; i >= 0; --i) {
13347            observers[i].onPackageAdded(packageName);
13348        }
13349    }
13350
13351    @Override
13352    public void notifyPackageRemoved(String packageName) {
13353        final PackageListObserver[] observers;
13354        synchronized (mPackages) {
13355            if (mPackageListObservers.size() == 0) {
13356                return;
13357            }
13358            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13359        }
13360        for (int i = observers.length - 1; i >= 0; --i) {
13361            observers[i].onPackageRemoved(packageName);
13362        }
13363    }
13364
13365    /**
13366     * Sends a broadcast for the given action.
13367     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13368     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13369     * the system and applications allowed to see instant applications to receive package
13370     * lifecycle events for instant applications.
13371     */
13372    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13373            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13374            int[] userIds, boolean isInstantApp)
13375                    throws RemoteException {
13376        for (int id : userIds) {
13377            final Intent intent = new Intent(action,
13378                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13379            final String[] requiredPermissions =
13380                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13381            if (extras != null) {
13382                intent.putExtras(extras);
13383            }
13384            if (targetPkg != null) {
13385                intent.setPackage(targetPkg);
13386            }
13387            // Modify the UID when posting to other users
13388            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13389            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13390                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13391                intent.putExtra(Intent.EXTRA_UID, uid);
13392            }
13393            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13394            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13395            if (DEBUG_BROADCASTS) {
13396                RuntimeException here = new RuntimeException("here");
13397                here.fillInStackTrace();
13398                Slog.d(TAG, "Sending to user " + id + ": "
13399                        + intent.toShortString(false, true, false, false)
13400                        + " " + intent.getExtras(), here);
13401            }
13402            am.broadcastIntent(null, intent, null, finishedReceiver,
13403                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13404                    null, finishedReceiver != null, false, id);
13405        }
13406    }
13407
13408    /**
13409     * Check if the external storage media is available. This is true if there
13410     * is a mounted external storage medium or if the external storage is
13411     * emulated.
13412     */
13413    private boolean isExternalMediaAvailable() {
13414        return mMediaMounted || Environment.isExternalStorageEmulated();
13415    }
13416
13417    @Override
13418    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13419        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13420            return null;
13421        }
13422        if (!isExternalMediaAvailable()) {
13423                // If the external storage is no longer mounted at this point,
13424                // the caller may not have been able to delete all of this
13425                // packages files and can not delete any more.  Bail.
13426            return null;
13427        }
13428        synchronized (mPackages) {
13429            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13430            if (lastPackage != null) {
13431                pkgs.remove(lastPackage);
13432            }
13433            if (pkgs.size() > 0) {
13434                return pkgs.get(0);
13435            }
13436        }
13437        return null;
13438    }
13439
13440    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13441        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13442                userId, andCode ? 1 : 0, packageName);
13443        if (mSystemReady) {
13444            msg.sendToTarget();
13445        } else {
13446            if (mPostSystemReadyMessages == null) {
13447                mPostSystemReadyMessages = new ArrayList<>();
13448            }
13449            mPostSystemReadyMessages.add(msg);
13450        }
13451    }
13452
13453    void startCleaningPackages() {
13454        // reader
13455        if (!isExternalMediaAvailable()) {
13456            return;
13457        }
13458        synchronized (mPackages) {
13459            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13460                return;
13461            }
13462        }
13463        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13464        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13465        IActivityManager am = ActivityManager.getService();
13466        if (am != null) {
13467            int dcsUid = -1;
13468            synchronized (mPackages) {
13469                if (!mDefaultContainerWhitelisted) {
13470                    mDefaultContainerWhitelisted = true;
13471                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13472                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13473                }
13474            }
13475            try {
13476                if (dcsUid > 0) {
13477                    am.backgroundWhitelistUid(dcsUid);
13478                }
13479                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13480                        UserHandle.USER_SYSTEM);
13481            } catch (RemoteException e) {
13482            }
13483        }
13484    }
13485
13486    /**
13487     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13488     * it is acting on behalf on an enterprise or the user).
13489     *
13490     * Note that the ordering of the conditionals in this method is important. The checks we perform
13491     * are as follows, in this order:
13492     *
13493     * 1) If the install is being performed by a system app, we can trust the app to have set the
13494     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13495     *    what it is.
13496     * 2) If the install is being performed by a device or profile owner app, the install reason
13497     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13498     *    set the install reason correctly. If the app targets an older SDK version where install
13499     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13500     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13501     * 3) In all other cases, the install is being performed by a regular app that is neither part
13502     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13503     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13504     *    set to enterprise policy and if so, change it to unknown instead.
13505     */
13506    private int fixUpInstallReason(String installerPackageName, int installerUid,
13507            int installReason) {
13508        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13509                == PERMISSION_GRANTED) {
13510            // If the install is being performed by a system app, we trust that app to have set the
13511            // install reason correctly.
13512            return installReason;
13513        }
13514
13515        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13516            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13517        if (dpm != null) {
13518            ComponentName owner = null;
13519            try {
13520                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13521                if (owner == null) {
13522                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13523                }
13524            } catch (RemoteException e) {
13525            }
13526            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13527                // If the install is being performed by a device or profile owner, the install
13528                // reason should be enterprise policy.
13529                return PackageManager.INSTALL_REASON_POLICY;
13530            }
13531        }
13532
13533        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13534            // If the install is being performed by a regular app (i.e. neither system app nor
13535            // device or profile owner), we have no reason to believe that the app is acting on
13536            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13537            // change it to unknown instead.
13538            return PackageManager.INSTALL_REASON_UNKNOWN;
13539        }
13540
13541        // If the install is being performed by a regular app and the install reason was set to any
13542        // value but enterprise policy, leave the install reason unchanged.
13543        return installReason;
13544    }
13545
13546    void installStage(String packageName, File stagedDir,
13547            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13548            String installerPackageName, int installerUid, UserHandle user,
13549            PackageParser.SigningDetails signingDetails) {
13550        if (DEBUG_INSTANT) {
13551            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13552                Slog.d(TAG, "Ephemeral install of " + packageName);
13553            }
13554        }
13555        final VerificationInfo verificationInfo = new VerificationInfo(
13556                sessionParams.originatingUri, sessionParams.referrerUri,
13557                sessionParams.originatingUid, installerUid);
13558
13559        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13560
13561        final Message msg = mHandler.obtainMessage(INIT_COPY);
13562        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13563                sessionParams.installReason);
13564        final InstallParams params = new InstallParams(origin, null, observer,
13565                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13566                verificationInfo, user, sessionParams.abiOverride,
13567                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13568        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13569        msg.obj = params;
13570
13571        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13572                System.identityHashCode(msg.obj));
13573        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13574                System.identityHashCode(msg.obj));
13575
13576        mHandler.sendMessage(msg);
13577    }
13578
13579    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13580            int userId) {
13581        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13582        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13583        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13584        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13585        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13586                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13587
13588        // Send a session commit broadcast
13589        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13590        info.installReason = pkgSetting.getInstallReason(userId);
13591        info.appPackageName = packageName;
13592        sendSessionCommitBroadcast(info, userId);
13593    }
13594
13595    @Override
13596    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13597            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13598        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13599            return;
13600        }
13601        Bundle extras = new Bundle(1);
13602        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13603        final int uid = UserHandle.getUid(
13604                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13605        extras.putInt(Intent.EXTRA_UID, uid);
13606
13607        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13608                packageName, extras, 0, null, null, userIds, instantUserIds);
13609        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13610            mHandler.post(() -> {
13611                        for (int userId : userIds) {
13612                            sendBootCompletedBroadcastToSystemApp(
13613                                    packageName, includeStopped, userId);
13614                        }
13615                    }
13616            );
13617        }
13618    }
13619
13620    /**
13621     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13622     * automatically without needing an explicit launch.
13623     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13624     */
13625    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13626            int userId) {
13627        // If user is not running, the app didn't miss any broadcast
13628        if (!mUserManagerInternal.isUserRunning(userId)) {
13629            return;
13630        }
13631        final IActivityManager am = ActivityManager.getService();
13632        try {
13633            // Deliver LOCKED_BOOT_COMPLETED first
13634            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13635                    .setPackage(packageName);
13636            if (includeStopped) {
13637                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13638            }
13639            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13640            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13641                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13642
13643            // Deliver BOOT_COMPLETED only if user is unlocked
13644            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13645                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13646                if (includeStopped) {
13647                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13648                }
13649                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13650                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13651            }
13652        } catch (RemoteException e) {
13653            throw e.rethrowFromSystemServer();
13654        }
13655    }
13656
13657    @Override
13658    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13659            int userId) {
13660        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13661        PackageSetting pkgSetting;
13662        final int callingUid = Binder.getCallingUid();
13663        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13664                true /* requireFullPermission */, true /* checkShell */,
13665                "setApplicationHiddenSetting for user " + userId);
13666
13667        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13668            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13669            return false;
13670        }
13671
13672        long callingId = Binder.clearCallingIdentity();
13673        try {
13674            boolean sendAdded = false;
13675            boolean sendRemoved = false;
13676            // writer
13677            synchronized (mPackages) {
13678                pkgSetting = mSettings.mPackages.get(packageName);
13679                if (pkgSetting == null) {
13680                    return false;
13681                }
13682                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13683                    return false;
13684                }
13685                // Do not allow "android" is being disabled
13686                if ("android".equals(packageName)) {
13687                    Slog.w(TAG, "Cannot hide package: android");
13688                    return false;
13689                }
13690                // Cannot hide static shared libs as they are considered
13691                // a part of the using app (emulating static linking). Also
13692                // static libs are installed always on internal storage.
13693                PackageParser.Package pkg = mPackages.get(packageName);
13694                if (pkg != null && pkg.staticSharedLibName != null) {
13695                    Slog.w(TAG, "Cannot hide package: " + packageName
13696                            + " providing static shared library: "
13697                            + pkg.staticSharedLibName);
13698                    return false;
13699                }
13700                // Only allow protected packages to hide themselves.
13701                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13702                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13703                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13704                    return false;
13705                }
13706
13707                if (pkgSetting.getHidden(userId) != hidden) {
13708                    pkgSetting.setHidden(hidden, userId);
13709                    mSettings.writePackageRestrictionsLPr(userId);
13710                    if (hidden) {
13711                        sendRemoved = true;
13712                    } else {
13713                        sendAdded = true;
13714                    }
13715                }
13716            }
13717            if (sendAdded) {
13718                sendPackageAddedForUser(packageName, pkgSetting, userId);
13719                return true;
13720            }
13721            if (sendRemoved) {
13722                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13723                        "hiding pkg");
13724                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13725                return true;
13726            }
13727        } finally {
13728            Binder.restoreCallingIdentity(callingId);
13729        }
13730        return false;
13731    }
13732
13733    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13734            int userId) {
13735        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13736        info.removedPackage = packageName;
13737        info.installerPackageName = pkgSetting.installerPackageName;
13738        info.removedUsers = new int[] {userId};
13739        info.broadcastUsers = new int[] {userId};
13740        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13741        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13742    }
13743
13744    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13745        if (pkgList.length > 0) {
13746            Bundle extras = new Bundle(1);
13747            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13748
13749            sendPackageBroadcast(
13750                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13751                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13752                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13753                    new int[] {userId}, null);
13754        }
13755    }
13756
13757    /**
13758     * Returns true if application is not found or there was an error. Otherwise it returns
13759     * the hidden state of the package for the given user.
13760     */
13761    @Override
13762    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13763        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13764        final int callingUid = Binder.getCallingUid();
13765        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13766                true /* requireFullPermission */, false /* checkShell */,
13767                "getApplicationHidden for user " + userId);
13768        PackageSetting ps;
13769        long callingId = Binder.clearCallingIdentity();
13770        try {
13771            // writer
13772            synchronized (mPackages) {
13773                ps = mSettings.mPackages.get(packageName);
13774                if (ps == null) {
13775                    return true;
13776                }
13777                if (filterAppAccessLPr(ps, callingUid, userId)) {
13778                    return true;
13779                }
13780                return ps.getHidden(userId);
13781            }
13782        } finally {
13783            Binder.restoreCallingIdentity(callingId);
13784        }
13785    }
13786
13787    /**
13788     * @hide
13789     */
13790    @Override
13791    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13792            int installReason) {
13793        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13794                null);
13795        PackageSetting pkgSetting;
13796        final int callingUid = Binder.getCallingUid();
13797        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13798                true /* requireFullPermission */, true /* checkShell */,
13799                "installExistingPackage for user " + userId);
13800        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13801            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13802        }
13803
13804        long callingId = Binder.clearCallingIdentity();
13805        try {
13806            boolean installed = false;
13807            final boolean instantApp =
13808                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13809            final boolean fullApp =
13810                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13811
13812            // writer
13813            synchronized (mPackages) {
13814                pkgSetting = mSettings.mPackages.get(packageName);
13815                if (pkgSetting == null) {
13816                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13817                }
13818                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13819                    // only allow the existing package to be used if it's installed as a full
13820                    // application for at least one user
13821                    boolean installAllowed = false;
13822                    for (int checkUserId : sUserManager.getUserIds()) {
13823                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13824                        if (installAllowed) {
13825                            break;
13826                        }
13827                    }
13828                    if (!installAllowed) {
13829                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13830                    }
13831                }
13832                if (!pkgSetting.getInstalled(userId)) {
13833                    pkgSetting.setInstalled(true, userId);
13834                    pkgSetting.setHidden(false, userId);
13835                    pkgSetting.setInstallReason(installReason, userId);
13836                    mSettings.writePackageRestrictionsLPr(userId);
13837                    mSettings.writeKernelMappingLPr(pkgSetting);
13838                    installed = true;
13839                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13840                    // upgrade app from instant to full; we don't allow app downgrade
13841                    installed = true;
13842                }
13843                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13844            }
13845
13846            if (installed) {
13847                if (pkgSetting.pkg != null) {
13848                    synchronized (mInstallLock) {
13849                        // We don't need to freeze for a brand new install
13850                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13851                    }
13852                }
13853                sendPackageAddedForUser(packageName, pkgSetting, userId);
13854                synchronized (mPackages) {
13855                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13856                }
13857            }
13858        } finally {
13859            Binder.restoreCallingIdentity(callingId);
13860        }
13861
13862        return PackageManager.INSTALL_SUCCEEDED;
13863    }
13864
13865    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13866            boolean instantApp, boolean fullApp) {
13867        // no state specified; do nothing
13868        if (!instantApp && !fullApp) {
13869            return;
13870        }
13871        if (userId != UserHandle.USER_ALL) {
13872            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13873                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13874            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13875                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13876            }
13877        } else {
13878            for (int currentUserId : sUserManager.getUserIds()) {
13879                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13880                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13881                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13882                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13883                }
13884            }
13885        }
13886    }
13887
13888    boolean isUserRestricted(int userId, String restrictionKey) {
13889        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13890        if (restrictions.getBoolean(restrictionKey, false)) {
13891            Log.w(TAG, "User is restricted: " + restrictionKey);
13892            return true;
13893        }
13894        return false;
13895    }
13896
13897    @Override
13898    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13899            int userId) {
13900        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13901        final int callingUid = Binder.getCallingUid();
13902        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13903                true /* requireFullPermission */, true /* checkShell */,
13904                "setPackagesSuspended for user " + userId);
13905
13906        if (ArrayUtils.isEmpty(packageNames)) {
13907            return packageNames;
13908        }
13909
13910        // List of package names for whom the suspended state has changed.
13911        List<String> changedPackages = new ArrayList<>(packageNames.length);
13912        // List of package names for whom the suspended state is not set as requested in this
13913        // method.
13914        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13915        long callingId = Binder.clearCallingIdentity();
13916        try {
13917            for (int i = 0; i < packageNames.length; i++) {
13918                String packageName = packageNames[i];
13919                boolean changed = false;
13920                final int appId;
13921                synchronized (mPackages) {
13922                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13923                    if (pkgSetting == null
13924                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13925                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13926                                + "\". Skipping suspending/un-suspending.");
13927                        unactionedPackages.add(packageName);
13928                        continue;
13929                    }
13930                    appId = pkgSetting.appId;
13931                    if (pkgSetting.getSuspended(userId) != suspended) {
13932                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13933                            unactionedPackages.add(packageName);
13934                            continue;
13935                        }
13936                        pkgSetting.setSuspended(suspended, userId);
13937                        mSettings.writePackageRestrictionsLPr(userId);
13938                        changed = true;
13939                        changedPackages.add(packageName);
13940                    }
13941                }
13942
13943                if (changed && suspended) {
13944                    killApplication(packageName, UserHandle.getUid(userId, appId),
13945                            "suspending package");
13946                }
13947            }
13948        } finally {
13949            Binder.restoreCallingIdentity(callingId);
13950        }
13951
13952        if (!changedPackages.isEmpty()) {
13953            sendPackagesSuspendedForUser(changedPackages.toArray(
13954                    new String[changedPackages.size()]), userId, suspended);
13955        }
13956
13957        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13958    }
13959
13960    @Override
13961    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13962        final int callingUid = Binder.getCallingUid();
13963        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13964                true /* requireFullPermission */, false /* checkShell */,
13965                "isPackageSuspendedForUser for user " + userId);
13966        synchronized (mPackages) {
13967            final PackageSetting ps = mSettings.mPackages.get(packageName);
13968            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13969                throw new IllegalArgumentException("Unknown target package: " + packageName);
13970            }
13971            return ps.getSuspended(userId);
13972        }
13973    }
13974
13975    @GuardedBy("mPackages")
13976    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13977        if (isPackageDeviceAdmin(packageName, userId)) {
13978            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13979                    + "\": has an active device admin");
13980            return false;
13981        }
13982
13983        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13984        if (packageName.equals(activeLauncherPackageName)) {
13985            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13986                    + "\": contains the active launcher");
13987            return false;
13988        }
13989
13990        if (packageName.equals(mRequiredInstallerPackage)) {
13991            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13992                    + "\": required for package installation");
13993            return false;
13994        }
13995
13996        if (packageName.equals(mRequiredUninstallerPackage)) {
13997            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13998                    + "\": required for package uninstallation");
13999            return false;
14000        }
14001
14002        if (packageName.equals(mRequiredVerifierPackage)) {
14003            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14004                    + "\": required for package verification");
14005            return false;
14006        }
14007
14008        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14009            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14010                    + "\": is the default dialer");
14011            return false;
14012        }
14013
14014        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14015            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14016                    + "\": protected package");
14017            return false;
14018        }
14019
14020        // Cannot suspend static shared libs as they are considered
14021        // a part of the using app (emulating static linking). Also
14022        // static libs are installed always on internal storage.
14023        PackageParser.Package pkg = mPackages.get(packageName);
14024        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14025            Slog.w(TAG, "Cannot suspend package: " + packageName
14026                    + " providing static shared library: "
14027                    + pkg.staticSharedLibName);
14028            return false;
14029        }
14030
14031        return true;
14032    }
14033
14034    private String getActiveLauncherPackageName(int userId) {
14035        Intent intent = new Intent(Intent.ACTION_MAIN);
14036        intent.addCategory(Intent.CATEGORY_HOME);
14037        ResolveInfo resolveInfo = resolveIntent(
14038                intent,
14039                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14040                PackageManager.MATCH_DEFAULT_ONLY,
14041                userId);
14042
14043        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14044    }
14045
14046    private String getDefaultDialerPackageName(int userId) {
14047        synchronized (mPackages) {
14048            return mSettings.getDefaultDialerPackageNameLPw(userId);
14049        }
14050    }
14051
14052    @Override
14053    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14054        mContext.enforceCallingOrSelfPermission(
14055                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14056                "Only package verification agents can verify applications");
14057
14058        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14059        final PackageVerificationResponse response = new PackageVerificationResponse(
14060                verificationCode, Binder.getCallingUid());
14061        msg.arg1 = id;
14062        msg.obj = response;
14063        mHandler.sendMessage(msg);
14064    }
14065
14066    @Override
14067    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14068            long millisecondsToDelay) {
14069        mContext.enforceCallingOrSelfPermission(
14070                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14071                "Only package verification agents can extend verification timeouts");
14072
14073        final PackageVerificationState state = mPendingVerification.get(id);
14074        final PackageVerificationResponse response = new PackageVerificationResponse(
14075                verificationCodeAtTimeout, Binder.getCallingUid());
14076
14077        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14078            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14079        }
14080        if (millisecondsToDelay < 0) {
14081            millisecondsToDelay = 0;
14082        }
14083        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14084                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14085            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14086        }
14087
14088        if ((state != null) && !state.timeoutExtended()) {
14089            state.extendTimeout();
14090
14091            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14092            msg.arg1 = id;
14093            msg.obj = response;
14094            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14095        }
14096    }
14097
14098    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14099            int verificationCode, UserHandle user) {
14100        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14101        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14102        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14103        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14104        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14105
14106        mContext.sendBroadcastAsUser(intent, user,
14107                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14108    }
14109
14110    private ComponentName matchComponentForVerifier(String packageName,
14111            List<ResolveInfo> receivers) {
14112        ActivityInfo targetReceiver = null;
14113
14114        final int NR = receivers.size();
14115        for (int i = 0; i < NR; i++) {
14116            final ResolveInfo info = receivers.get(i);
14117            if (info.activityInfo == null) {
14118                continue;
14119            }
14120
14121            if (packageName.equals(info.activityInfo.packageName)) {
14122                targetReceiver = info.activityInfo;
14123                break;
14124            }
14125        }
14126
14127        if (targetReceiver == null) {
14128            return null;
14129        }
14130
14131        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14132    }
14133
14134    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14135            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14136        if (pkgInfo.verifiers.length == 0) {
14137            return null;
14138        }
14139
14140        final int N = pkgInfo.verifiers.length;
14141        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14142        for (int i = 0; i < N; i++) {
14143            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14144
14145            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14146                    receivers);
14147            if (comp == null) {
14148                continue;
14149            }
14150
14151            final int verifierUid = getUidForVerifier(verifierInfo);
14152            if (verifierUid == -1) {
14153                continue;
14154            }
14155
14156            if (DEBUG_VERIFY) {
14157                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14158                        + " with the correct signature");
14159            }
14160            sufficientVerifiers.add(comp);
14161            verificationState.addSufficientVerifier(verifierUid);
14162        }
14163
14164        return sufficientVerifiers;
14165    }
14166
14167    private int getUidForVerifier(VerifierInfo verifierInfo) {
14168        synchronized (mPackages) {
14169            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14170            if (pkg == null) {
14171                return -1;
14172            } else if (pkg.mSigningDetails.signatures.length != 1) {
14173                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14174                        + " has more than one signature; ignoring");
14175                return -1;
14176            }
14177
14178            /*
14179             * If the public key of the package's signature does not match
14180             * our expected public key, then this is a different package and
14181             * we should skip.
14182             */
14183
14184            final byte[] expectedPublicKey;
14185            try {
14186                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14187                final PublicKey publicKey = verifierSig.getPublicKey();
14188                expectedPublicKey = publicKey.getEncoded();
14189            } catch (CertificateException e) {
14190                return -1;
14191            }
14192
14193            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14194
14195            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14196                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14197                        + " does not have the expected public key; ignoring");
14198                return -1;
14199            }
14200
14201            return pkg.applicationInfo.uid;
14202        }
14203    }
14204
14205    @Override
14206    public void finishPackageInstall(int token, boolean didLaunch) {
14207        enforceSystemOrRoot("Only the system is allowed to finish installs");
14208
14209        if (DEBUG_INSTALL) {
14210            Slog.v(TAG, "BM finishing package install for " + token);
14211        }
14212        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14213
14214        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14215        mHandler.sendMessage(msg);
14216    }
14217
14218    /**
14219     * Get the verification agent timeout.  Used for both the APK verifier and the
14220     * intent filter verifier.
14221     *
14222     * @return verification timeout in milliseconds
14223     */
14224    private long getVerificationTimeout() {
14225        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14226                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14227                DEFAULT_VERIFICATION_TIMEOUT);
14228    }
14229
14230    /**
14231     * Get the default verification agent response code.
14232     *
14233     * @return default verification response code
14234     */
14235    private int getDefaultVerificationResponse(UserHandle user) {
14236        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14237            return PackageManager.VERIFICATION_REJECT;
14238        }
14239        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14240                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14241                DEFAULT_VERIFICATION_RESPONSE);
14242    }
14243
14244    /**
14245     * Check whether or not package verification has been enabled.
14246     *
14247     * @return true if verification should be performed
14248     */
14249    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14250        if (!DEFAULT_VERIFY_ENABLE) {
14251            return false;
14252        }
14253
14254        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14255
14256        // Check if installing from ADB
14257        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14258            // Do not run verification in a test harness environment
14259            if (ActivityManager.isRunningInTestHarness()) {
14260                return false;
14261            }
14262            if (ensureVerifyAppsEnabled) {
14263                return true;
14264            }
14265            // Check if the developer does not want package verification for ADB installs
14266            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14267                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14268                return false;
14269            }
14270        } else {
14271            // only when not installed from ADB, skip verification for instant apps when
14272            // the installer and verifier are the same.
14273            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14274                if (mInstantAppInstallerActivity != null
14275                        && mInstantAppInstallerActivity.packageName.equals(
14276                                mRequiredVerifierPackage)) {
14277                    try {
14278                        mContext.getSystemService(AppOpsManager.class)
14279                                .checkPackage(installerUid, mRequiredVerifierPackage);
14280                        if (DEBUG_VERIFY) {
14281                            Slog.i(TAG, "disable verification for instant app");
14282                        }
14283                        return false;
14284                    } catch (SecurityException ignore) { }
14285                }
14286            }
14287        }
14288
14289        if (ensureVerifyAppsEnabled) {
14290            return true;
14291        }
14292
14293        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14294                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14295    }
14296
14297    @Override
14298    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14299            throws RemoteException {
14300        mContext.enforceCallingOrSelfPermission(
14301                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14302                "Only intentfilter verification agents can verify applications");
14303
14304        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14305        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14306                Binder.getCallingUid(), verificationCode, failedDomains);
14307        msg.arg1 = id;
14308        msg.obj = response;
14309        mHandler.sendMessage(msg);
14310    }
14311
14312    @Override
14313    public int getIntentVerificationStatus(String packageName, int userId) {
14314        final int callingUid = Binder.getCallingUid();
14315        if (UserHandle.getUserId(callingUid) != userId) {
14316            mContext.enforceCallingOrSelfPermission(
14317                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14318                    "getIntentVerificationStatus" + userId);
14319        }
14320        if (getInstantAppPackageName(callingUid) != null) {
14321            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14322        }
14323        synchronized (mPackages) {
14324            final PackageSetting ps = mSettings.mPackages.get(packageName);
14325            if (ps == null
14326                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14327                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14328            }
14329            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14330        }
14331    }
14332
14333    @Override
14334    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14335        mContext.enforceCallingOrSelfPermission(
14336                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14337
14338        boolean result = false;
14339        synchronized (mPackages) {
14340            final PackageSetting ps = mSettings.mPackages.get(packageName);
14341            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14342                return false;
14343            }
14344            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14345        }
14346        if (result) {
14347            scheduleWritePackageRestrictionsLocked(userId);
14348        }
14349        return result;
14350    }
14351
14352    @Override
14353    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14354            String packageName) {
14355        final int callingUid = Binder.getCallingUid();
14356        if (getInstantAppPackageName(callingUid) != null) {
14357            return ParceledListSlice.emptyList();
14358        }
14359        synchronized (mPackages) {
14360            final PackageSetting ps = mSettings.mPackages.get(packageName);
14361            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14362                return ParceledListSlice.emptyList();
14363            }
14364            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14365        }
14366    }
14367
14368    @Override
14369    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14370        if (TextUtils.isEmpty(packageName)) {
14371            return ParceledListSlice.emptyList();
14372        }
14373        final int callingUid = Binder.getCallingUid();
14374        final int callingUserId = UserHandle.getUserId(callingUid);
14375        synchronized (mPackages) {
14376            PackageParser.Package pkg = mPackages.get(packageName);
14377            if (pkg == null || pkg.activities == null) {
14378                return ParceledListSlice.emptyList();
14379            }
14380            if (pkg.mExtras == null) {
14381                return ParceledListSlice.emptyList();
14382            }
14383            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14384            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14385                return ParceledListSlice.emptyList();
14386            }
14387            final int count = pkg.activities.size();
14388            ArrayList<IntentFilter> result = new ArrayList<>();
14389            for (int n=0; n<count; n++) {
14390                PackageParser.Activity activity = pkg.activities.get(n);
14391                if (activity.intents != null && activity.intents.size() > 0) {
14392                    result.addAll(activity.intents);
14393                }
14394            }
14395            return new ParceledListSlice<>(result);
14396        }
14397    }
14398
14399    @Override
14400    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14401        mContext.enforceCallingOrSelfPermission(
14402                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14403        if (UserHandle.getCallingUserId() != userId) {
14404            mContext.enforceCallingOrSelfPermission(
14405                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14406        }
14407
14408        synchronized (mPackages) {
14409            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14410            if (packageName != null) {
14411                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14412                        packageName, userId);
14413            }
14414            return result;
14415        }
14416    }
14417
14418    @Override
14419    public String getDefaultBrowserPackageName(int userId) {
14420        if (UserHandle.getCallingUserId() != userId) {
14421            mContext.enforceCallingOrSelfPermission(
14422                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14423        }
14424        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14425            return null;
14426        }
14427        synchronized (mPackages) {
14428            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14429        }
14430    }
14431
14432    /**
14433     * Get the "allow unknown sources" setting.
14434     *
14435     * @return the current "allow unknown sources" setting
14436     */
14437    private int getUnknownSourcesSettings() {
14438        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14439                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14440                -1);
14441    }
14442
14443    @Override
14444    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14445        final int callingUid = Binder.getCallingUid();
14446        if (getInstantAppPackageName(callingUid) != null) {
14447            return;
14448        }
14449        // writer
14450        synchronized (mPackages) {
14451            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14452            if (targetPackageSetting == null
14453                    || filterAppAccessLPr(
14454                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14455                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14456            }
14457
14458            PackageSetting installerPackageSetting;
14459            if (installerPackageName != null) {
14460                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14461                if (installerPackageSetting == null) {
14462                    throw new IllegalArgumentException("Unknown installer package: "
14463                            + installerPackageName);
14464                }
14465            } else {
14466                installerPackageSetting = null;
14467            }
14468
14469            Signature[] callerSignature;
14470            Object obj = mSettings.getUserIdLPr(callingUid);
14471            if (obj != null) {
14472                if (obj instanceof SharedUserSetting) {
14473                    callerSignature =
14474                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14475                } else if (obj instanceof PackageSetting) {
14476                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14477                } else {
14478                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14479                }
14480            } else {
14481                throw new SecurityException("Unknown calling UID: " + callingUid);
14482            }
14483
14484            // Verify: can't set installerPackageName to a package that is
14485            // not signed with the same cert as the caller.
14486            if (installerPackageSetting != null) {
14487                if (compareSignatures(callerSignature,
14488                        installerPackageSetting.signatures.mSigningDetails.signatures)
14489                        != PackageManager.SIGNATURE_MATCH) {
14490                    throw new SecurityException(
14491                            "Caller does not have same cert as new installer package "
14492                            + installerPackageName);
14493                }
14494            }
14495
14496            // Verify: if target already has an installer package, it must
14497            // be signed with the same cert as the caller.
14498            if (targetPackageSetting.installerPackageName != null) {
14499                PackageSetting setting = mSettings.mPackages.get(
14500                        targetPackageSetting.installerPackageName);
14501                // If the currently set package isn't valid, then it's always
14502                // okay to change it.
14503                if (setting != null) {
14504                    if (compareSignatures(callerSignature,
14505                            setting.signatures.mSigningDetails.signatures)
14506                            != PackageManager.SIGNATURE_MATCH) {
14507                        throw new SecurityException(
14508                                "Caller does not have same cert as old installer package "
14509                                + targetPackageSetting.installerPackageName);
14510                    }
14511                }
14512            }
14513
14514            // Okay!
14515            targetPackageSetting.installerPackageName = installerPackageName;
14516            if (installerPackageName != null) {
14517                mSettings.mInstallerPackages.add(installerPackageName);
14518            }
14519            scheduleWriteSettingsLocked();
14520        }
14521    }
14522
14523    @Override
14524    public void setApplicationCategoryHint(String packageName, int categoryHint,
14525            String callerPackageName) {
14526        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14527            throw new SecurityException("Instant applications don't have access to this method");
14528        }
14529        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14530                callerPackageName);
14531        synchronized (mPackages) {
14532            PackageSetting ps = mSettings.mPackages.get(packageName);
14533            if (ps == null) {
14534                throw new IllegalArgumentException("Unknown target package " + packageName);
14535            }
14536            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14537                throw new IllegalArgumentException("Unknown target package " + packageName);
14538            }
14539            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14540                throw new IllegalArgumentException("Calling package " + callerPackageName
14541                        + " is not installer for " + packageName);
14542            }
14543
14544            if (ps.categoryHint != categoryHint) {
14545                ps.categoryHint = categoryHint;
14546                scheduleWriteSettingsLocked();
14547            }
14548        }
14549    }
14550
14551    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14552        // Queue up an async operation since the package installation may take a little while.
14553        mHandler.post(new Runnable() {
14554            public void run() {
14555                mHandler.removeCallbacks(this);
14556                 // Result object to be returned
14557                PackageInstalledInfo res = new PackageInstalledInfo();
14558                res.setReturnCode(currentStatus);
14559                res.uid = -1;
14560                res.pkg = null;
14561                res.removedInfo = null;
14562                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14563                    args.doPreInstall(res.returnCode);
14564                    synchronized (mInstallLock) {
14565                        installPackageTracedLI(args, res);
14566                    }
14567                    args.doPostInstall(res.returnCode, res.uid);
14568                }
14569
14570                // A restore should be performed at this point if (a) the install
14571                // succeeded, (b) the operation is not an update, and (c) the new
14572                // package has not opted out of backup participation.
14573                final boolean update = res.removedInfo != null
14574                        && res.removedInfo.removedPackage != null;
14575                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14576                boolean doRestore = !update
14577                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14578
14579                // Set up the post-install work request bookkeeping.  This will be used
14580                // and cleaned up by the post-install event handling regardless of whether
14581                // there's a restore pass performed.  Token values are >= 1.
14582                int token;
14583                if (mNextInstallToken < 0) mNextInstallToken = 1;
14584                token = mNextInstallToken++;
14585
14586                PostInstallData data = new PostInstallData(args, res);
14587                mRunningInstalls.put(token, data);
14588                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14589
14590                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14591                    // Pass responsibility to the Backup Manager.  It will perform a
14592                    // restore if appropriate, then pass responsibility back to the
14593                    // Package Manager to run the post-install observer callbacks
14594                    // and broadcasts.
14595                    IBackupManager bm = IBackupManager.Stub.asInterface(
14596                            ServiceManager.getService(Context.BACKUP_SERVICE));
14597                    if (bm != null) {
14598                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14599                                + " to BM for possible restore");
14600                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14601                        try {
14602                            // TODO: http://b/22388012
14603                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14604                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14605                            } else {
14606                                doRestore = false;
14607                            }
14608                        } catch (RemoteException e) {
14609                            // can't happen; the backup manager is local
14610                        } catch (Exception e) {
14611                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14612                            doRestore = false;
14613                        }
14614                    } else {
14615                        Slog.e(TAG, "Backup Manager not found!");
14616                        doRestore = false;
14617                    }
14618                }
14619
14620                if (!doRestore) {
14621                    // No restore possible, or the Backup Manager was mysteriously not
14622                    // available -- just fire the post-install work request directly.
14623                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14624
14625                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14626
14627                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14628                    mHandler.sendMessage(msg);
14629                }
14630            }
14631        });
14632    }
14633
14634    /**
14635     * Callback from PackageSettings whenever an app is first transitioned out of the
14636     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14637     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14638     * here whether the app is the target of an ongoing install, and only send the
14639     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14640     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14641     * handling.
14642     */
14643    void notifyFirstLaunch(final String packageName, final String installerPackage,
14644            final int userId) {
14645        // Serialize this with the rest of the install-process message chain.  In the
14646        // restore-at-install case, this Runnable will necessarily run before the
14647        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14648        // are coherent.  In the non-restore case, the app has already completed install
14649        // and been launched through some other means, so it is not in a problematic
14650        // state for observers to see the FIRST_LAUNCH signal.
14651        mHandler.post(new Runnable() {
14652            @Override
14653            public void run() {
14654                for (int i = 0; i < mRunningInstalls.size(); i++) {
14655                    final PostInstallData data = mRunningInstalls.valueAt(i);
14656                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14657                        continue;
14658                    }
14659                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14660                        // right package; but is it for the right user?
14661                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14662                            if (userId == data.res.newUsers[uIndex]) {
14663                                if (DEBUG_BACKUP) {
14664                                    Slog.i(TAG, "Package " + packageName
14665                                            + " being restored so deferring FIRST_LAUNCH");
14666                                }
14667                                return;
14668                            }
14669                        }
14670                    }
14671                }
14672                // didn't find it, so not being restored
14673                if (DEBUG_BACKUP) {
14674                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14675                }
14676                final boolean isInstantApp = isInstantApp(packageName, userId);
14677                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14678                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14679                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14680            }
14681        });
14682    }
14683
14684    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14685            int[] userIds, int[] instantUserIds) {
14686        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14687                installerPkg, null, userIds, instantUserIds);
14688    }
14689
14690    private abstract class HandlerParams {
14691        private static final int MAX_RETRIES = 4;
14692
14693        /**
14694         * Number of times startCopy() has been attempted and had a non-fatal
14695         * error.
14696         */
14697        private int mRetries = 0;
14698
14699        /** User handle for the user requesting the information or installation. */
14700        private final UserHandle mUser;
14701        String traceMethod;
14702        int traceCookie;
14703
14704        HandlerParams(UserHandle user) {
14705            mUser = user;
14706        }
14707
14708        UserHandle getUser() {
14709            return mUser;
14710        }
14711
14712        HandlerParams setTraceMethod(String traceMethod) {
14713            this.traceMethod = traceMethod;
14714            return this;
14715        }
14716
14717        HandlerParams setTraceCookie(int traceCookie) {
14718            this.traceCookie = traceCookie;
14719            return this;
14720        }
14721
14722        final boolean startCopy() {
14723            boolean res;
14724            try {
14725                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14726
14727                if (++mRetries > MAX_RETRIES) {
14728                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14729                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14730                    handleServiceError();
14731                    return false;
14732                } else {
14733                    handleStartCopy();
14734                    res = true;
14735                }
14736            } catch (RemoteException e) {
14737                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14738                mHandler.sendEmptyMessage(MCS_RECONNECT);
14739                res = false;
14740            }
14741            handleReturnCode();
14742            return res;
14743        }
14744
14745        final void serviceError() {
14746            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14747            handleServiceError();
14748            handleReturnCode();
14749        }
14750
14751        abstract void handleStartCopy() throws RemoteException;
14752        abstract void handleServiceError();
14753        abstract void handleReturnCode();
14754    }
14755
14756    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14757        for (File path : paths) {
14758            try {
14759                mcs.clearDirectory(path.getAbsolutePath());
14760            } catch (RemoteException e) {
14761            }
14762        }
14763    }
14764
14765    static class OriginInfo {
14766        /**
14767         * Location where install is coming from, before it has been
14768         * copied/renamed into place. This could be a single monolithic APK
14769         * file, or a cluster directory. This location may be untrusted.
14770         */
14771        final File file;
14772
14773        /**
14774         * Flag indicating that {@link #file} or {@link #cid} has already been
14775         * staged, meaning downstream users don't need to defensively copy the
14776         * contents.
14777         */
14778        final boolean staged;
14779
14780        /**
14781         * Flag indicating that {@link #file} or {@link #cid} is an already
14782         * installed app that is being moved.
14783         */
14784        final boolean existing;
14785
14786        final String resolvedPath;
14787        final File resolvedFile;
14788
14789        static OriginInfo fromNothing() {
14790            return new OriginInfo(null, false, false);
14791        }
14792
14793        static OriginInfo fromUntrustedFile(File file) {
14794            return new OriginInfo(file, false, false);
14795        }
14796
14797        static OriginInfo fromExistingFile(File file) {
14798            return new OriginInfo(file, false, true);
14799        }
14800
14801        static OriginInfo fromStagedFile(File file) {
14802            return new OriginInfo(file, true, false);
14803        }
14804
14805        private OriginInfo(File file, boolean staged, boolean existing) {
14806            this.file = file;
14807            this.staged = staged;
14808            this.existing = existing;
14809
14810            if (file != null) {
14811                resolvedPath = file.getAbsolutePath();
14812                resolvedFile = file;
14813            } else {
14814                resolvedPath = null;
14815                resolvedFile = null;
14816            }
14817        }
14818    }
14819
14820    static class MoveInfo {
14821        final int moveId;
14822        final String fromUuid;
14823        final String toUuid;
14824        final String packageName;
14825        final String dataAppName;
14826        final int appId;
14827        final String seinfo;
14828        final int targetSdkVersion;
14829
14830        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14831                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14832            this.moveId = moveId;
14833            this.fromUuid = fromUuid;
14834            this.toUuid = toUuid;
14835            this.packageName = packageName;
14836            this.dataAppName = dataAppName;
14837            this.appId = appId;
14838            this.seinfo = seinfo;
14839            this.targetSdkVersion = targetSdkVersion;
14840        }
14841    }
14842
14843    static class VerificationInfo {
14844        /** A constant used to indicate that a uid value is not present. */
14845        public static final int NO_UID = -1;
14846
14847        /** URI referencing where the package was downloaded from. */
14848        final Uri originatingUri;
14849
14850        /** HTTP referrer URI associated with the originatingURI. */
14851        final Uri referrer;
14852
14853        /** UID of the application that the install request originated from. */
14854        final int originatingUid;
14855
14856        /** UID of application requesting the install */
14857        final int installerUid;
14858
14859        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14860            this.originatingUri = originatingUri;
14861            this.referrer = referrer;
14862            this.originatingUid = originatingUid;
14863            this.installerUid = installerUid;
14864        }
14865    }
14866
14867    class InstallParams extends HandlerParams {
14868        final OriginInfo origin;
14869        final MoveInfo move;
14870        final IPackageInstallObserver2 observer;
14871        int installFlags;
14872        final String installerPackageName;
14873        final String volumeUuid;
14874        private InstallArgs mArgs;
14875        private int mRet;
14876        final String packageAbiOverride;
14877        final String[] grantedRuntimePermissions;
14878        final VerificationInfo verificationInfo;
14879        final PackageParser.SigningDetails signingDetails;
14880        final int installReason;
14881
14882        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14883                int installFlags, String installerPackageName, String volumeUuid,
14884                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14885                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14886            super(user);
14887            this.origin = origin;
14888            this.move = move;
14889            this.observer = observer;
14890            this.installFlags = installFlags;
14891            this.installerPackageName = installerPackageName;
14892            this.volumeUuid = volumeUuid;
14893            this.verificationInfo = verificationInfo;
14894            this.packageAbiOverride = packageAbiOverride;
14895            this.grantedRuntimePermissions = grantedPermissions;
14896            this.signingDetails = signingDetails;
14897            this.installReason = installReason;
14898        }
14899
14900        @Override
14901        public String toString() {
14902            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14903                    + " file=" + origin.file + "}";
14904        }
14905
14906        private int installLocationPolicy(PackageInfoLite pkgLite) {
14907            String packageName = pkgLite.packageName;
14908            int installLocation = pkgLite.installLocation;
14909            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14910            // reader
14911            synchronized (mPackages) {
14912                // Currently installed package which the new package is attempting to replace or
14913                // null if no such package is installed.
14914                PackageParser.Package installedPkg = mPackages.get(packageName);
14915                // Package which currently owns the data which the new package will own if installed.
14916                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14917                // will be null whereas dataOwnerPkg will contain information about the package
14918                // which was uninstalled while keeping its data.
14919                PackageParser.Package dataOwnerPkg = installedPkg;
14920                if (dataOwnerPkg  == null) {
14921                    PackageSetting ps = mSettings.mPackages.get(packageName);
14922                    if (ps != null) {
14923                        dataOwnerPkg = ps.pkg;
14924                    }
14925                }
14926
14927                if (dataOwnerPkg != null) {
14928                    // If installed, the package will get access to data left on the device by its
14929                    // predecessor. As a security measure, this is permited only if this is not a
14930                    // version downgrade or if the predecessor package is marked as debuggable and
14931                    // a downgrade is explicitly requested.
14932                    //
14933                    // On debuggable platform builds, downgrades are permitted even for
14934                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14935                    // not offer security guarantees and thus it's OK to disable some security
14936                    // mechanisms to make debugging/testing easier on those builds. However, even on
14937                    // debuggable builds downgrades of packages are permitted only if requested via
14938                    // installFlags. This is because we aim to keep the behavior of debuggable
14939                    // platform builds as close as possible to the behavior of non-debuggable
14940                    // platform builds.
14941                    final boolean downgradeRequested =
14942                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14943                    final boolean packageDebuggable =
14944                                (dataOwnerPkg.applicationInfo.flags
14945                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14946                    final boolean downgradePermitted =
14947                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14948                    if (!downgradePermitted) {
14949                        try {
14950                            checkDowngrade(dataOwnerPkg, pkgLite);
14951                        } catch (PackageManagerException e) {
14952                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14953                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14954                        }
14955                    }
14956                }
14957
14958                if (installedPkg != null) {
14959                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14960                        // Check for updated system application.
14961                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14962                            if (onSd) {
14963                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14964                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14965                            }
14966                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14967                        } else {
14968                            if (onSd) {
14969                                // Install flag overrides everything.
14970                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14971                            }
14972                            // If current upgrade specifies particular preference
14973                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14974                                // Application explicitly specified internal.
14975                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14976                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14977                                // App explictly prefers external. Let policy decide
14978                            } else {
14979                                // Prefer previous location
14980                                if (isExternal(installedPkg)) {
14981                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14982                                }
14983                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14984                            }
14985                        }
14986                    } else {
14987                        // Invalid install. Return error code
14988                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14989                    }
14990                }
14991            }
14992            // All the special cases have been taken care of.
14993            // Return result based on recommended install location.
14994            if (onSd) {
14995                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14996            }
14997            return pkgLite.recommendedInstallLocation;
14998        }
14999
15000        /*
15001         * Invoke remote method to get package information and install
15002         * location values. Override install location based on default
15003         * policy if needed and then create install arguments based
15004         * on the install location.
15005         */
15006        public void handleStartCopy() throws RemoteException {
15007            int ret = PackageManager.INSTALL_SUCCEEDED;
15008
15009            // If we're already staged, we've firmly committed to an install location
15010            if (origin.staged) {
15011                if (origin.file != null) {
15012                    installFlags |= PackageManager.INSTALL_INTERNAL;
15013                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15014                } else {
15015                    throw new IllegalStateException("Invalid stage location");
15016                }
15017            }
15018
15019            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15020            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15021            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15022            PackageInfoLite pkgLite = null;
15023
15024            if (onInt && onSd) {
15025                // Check if both bits are set.
15026                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15027                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15028            } else if (onSd && ephemeral) {
15029                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15030                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15031            } else {
15032                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15033                        packageAbiOverride);
15034
15035                if (DEBUG_INSTANT && ephemeral) {
15036                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15037                }
15038
15039                /*
15040                 * If we have too little free space, try to free cache
15041                 * before giving up.
15042                 */
15043                if (!origin.staged && pkgLite.recommendedInstallLocation
15044                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15045                    // TODO: focus freeing disk space on the target device
15046                    final StorageManager storage = StorageManager.from(mContext);
15047                    final long lowThreshold = storage.getStorageLowBytes(
15048                            Environment.getDataDirectory());
15049
15050                    final long sizeBytes = mContainerService.calculateInstalledSize(
15051                            origin.resolvedPath, packageAbiOverride);
15052
15053                    try {
15054                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15055                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15056                                installFlags, packageAbiOverride);
15057                    } catch (InstallerException e) {
15058                        Slog.w(TAG, "Failed to free cache", e);
15059                    }
15060
15061                    /*
15062                     * The cache free must have deleted the file we
15063                     * downloaded to install.
15064                     *
15065                     * TODO: fix the "freeCache" call to not delete
15066                     *       the file we care about.
15067                     */
15068                    if (pkgLite.recommendedInstallLocation
15069                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15070                        pkgLite.recommendedInstallLocation
15071                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15072                    }
15073                }
15074            }
15075
15076            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15077                int loc = pkgLite.recommendedInstallLocation;
15078                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15079                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15080                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15081                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15082                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15083                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15084                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15085                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15086                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15087                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15088                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15089                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15090                } else {
15091                    // Override with defaults if needed.
15092                    loc = installLocationPolicy(pkgLite);
15093                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15094                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15095                    } else if (!onSd && !onInt) {
15096                        // Override install location with flags
15097                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15098                            // Set the flag to install on external media.
15099                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15100                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15101                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15102                            if (DEBUG_INSTANT) {
15103                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15104                            }
15105                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15106                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15107                                    |PackageManager.INSTALL_INTERNAL);
15108                        } else {
15109                            // Make sure the flag for installing on external
15110                            // media is unset
15111                            installFlags |= PackageManager.INSTALL_INTERNAL;
15112                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15113                        }
15114                    }
15115                }
15116            }
15117
15118            final InstallArgs args = createInstallArgs(this);
15119            mArgs = args;
15120
15121            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15122                // TODO: http://b/22976637
15123                // Apps installed for "all" users use the device owner to verify the app
15124                UserHandle verifierUser = getUser();
15125                if (verifierUser == UserHandle.ALL) {
15126                    verifierUser = UserHandle.SYSTEM;
15127                }
15128
15129                /*
15130                 * Determine if we have any installed package verifiers. If we
15131                 * do, then we'll defer to them to verify the packages.
15132                 */
15133                final int requiredUid = mRequiredVerifierPackage == null ? -1
15134                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15135                                verifierUser.getIdentifier());
15136                final int installerUid =
15137                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15138                if (!origin.existing && requiredUid != -1
15139                        && isVerificationEnabled(
15140                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15141                    final Intent verification = new Intent(
15142                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15143                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15144                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15145                            PACKAGE_MIME_TYPE);
15146                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15147
15148                    // Query all live verifiers based on current user state
15149                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15150                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15151                            false /*allowDynamicSplits*/);
15152
15153                    if (DEBUG_VERIFY) {
15154                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15155                                + verification.toString() + " with " + pkgLite.verifiers.length
15156                                + " optional verifiers");
15157                    }
15158
15159                    final int verificationId = mPendingVerificationToken++;
15160
15161                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15162
15163                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15164                            installerPackageName);
15165
15166                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15167                            installFlags);
15168
15169                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15170                            pkgLite.packageName);
15171
15172                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15173                            pkgLite.versionCode);
15174
15175                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15176                            pkgLite.getLongVersionCode());
15177
15178                    if (verificationInfo != null) {
15179                        if (verificationInfo.originatingUri != null) {
15180                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15181                                    verificationInfo.originatingUri);
15182                        }
15183                        if (verificationInfo.referrer != null) {
15184                            verification.putExtra(Intent.EXTRA_REFERRER,
15185                                    verificationInfo.referrer);
15186                        }
15187                        if (verificationInfo.originatingUid >= 0) {
15188                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15189                                    verificationInfo.originatingUid);
15190                        }
15191                        if (verificationInfo.installerUid >= 0) {
15192                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15193                                    verificationInfo.installerUid);
15194                        }
15195                    }
15196
15197                    final PackageVerificationState verificationState = new PackageVerificationState(
15198                            requiredUid, args);
15199
15200                    mPendingVerification.append(verificationId, verificationState);
15201
15202                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15203                            receivers, verificationState);
15204
15205                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15206                    final long idleDuration = getVerificationTimeout();
15207
15208                    /*
15209                     * If any sufficient verifiers were listed in the package
15210                     * manifest, attempt to ask them.
15211                     */
15212                    if (sufficientVerifiers != null) {
15213                        final int N = sufficientVerifiers.size();
15214                        if (N == 0) {
15215                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15216                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15217                        } else {
15218                            for (int i = 0; i < N; i++) {
15219                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15220                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15221                                        verifierComponent.getPackageName(), idleDuration,
15222                                        verifierUser.getIdentifier(), false, "package verifier");
15223
15224                                final Intent sufficientIntent = new Intent(verification);
15225                                sufficientIntent.setComponent(verifierComponent);
15226                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15227                            }
15228                        }
15229                    }
15230
15231                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15232                            mRequiredVerifierPackage, receivers);
15233                    if (ret == PackageManager.INSTALL_SUCCEEDED
15234                            && mRequiredVerifierPackage != null) {
15235                        Trace.asyncTraceBegin(
15236                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15237                        /*
15238                         * Send the intent to the required verification agent,
15239                         * but only start the verification timeout after the
15240                         * target BroadcastReceivers have run.
15241                         */
15242                        verification.setComponent(requiredVerifierComponent);
15243                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15244                                mRequiredVerifierPackage, idleDuration,
15245                                verifierUser.getIdentifier(), false, "package verifier");
15246                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15247                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15248                                new BroadcastReceiver() {
15249                                    @Override
15250                                    public void onReceive(Context context, Intent intent) {
15251                                        final Message msg = mHandler
15252                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15253                                        msg.arg1 = verificationId;
15254                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15255                                    }
15256                                }, null, 0, null, null);
15257
15258                        /*
15259                         * We don't want the copy to proceed until verification
15260                         * succeeds, so null out this field.
15261                         */
15262                        mArgs = null;
15263                    }
15264                } else {
15265                    /*
15266                     * No package verification is enabled, so immediately start
15267                     * the remote call to initiate copy using temporary file.
15268                     */
15269                    ret = args.copyApk(mContainerService, true);
15270                }
15271            }
15272
15273            mRet = ret;
15274        }
15275
15276        @Override
15277        void handleReturnCode() {
15278            // If mArgs is null, then MCS couldn't be reached. When it
15279            // reconnects, it will try again to install. At that point, this
15280            // will succeed.
15281            if (mArgs != null) {
15282                processPendingInstall(mArgs, mRet);
15283            }
15284        }
15285
15286        @Override
15287        void handleServiceError() {
15288            mArgs = createInstallArgs(this);
15289            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15290        }
15291    }
15292
15293    private InstallArgs createInstallArgs(InstallParams params) {
15294        if (params.move != null) {
15295            return new MoveInstallArgs(params);
15296        } else {
15297            return new FileInstallArgs(params);
15298        }
15299    }
15300
15301    /**
15302     * Create args that describe an existing installed package. Typically used
15303     * when cleaning up old installs, or used as a move source.
15304     */
15305    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15306            String resourcePath, String[] instructionSets) {
15307        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15308    }
15309
15310    static abstract class InstallArgs {
15311        /** @see InstallParams#origin */
15312        final OriginInfo origin;
15313        /** @see InstallParams#move */
15314        final MoveInfo move;
15315
15316        final IPackageInstallObserver2 observer;
15317        // Always refers to PackageManager flags only
15318        final int installFlags;
15319        final String installerPackageName;
15320        final String volumeUuid;
15321        final UserHandle user;
15322        final String abiOverride;
15323        final String[] installGrantPermissions;
15324        /** If non-null, drop an async trace when the install completes */
15325        final String traceMethod;
15326        final int traceCookie;
15327        final PackageParser.SigningDetails signingDetails;
15328        final int installReason;
15329
15330        // The list of instruction sets supported by this app. This is currently
15331        // only used during the rmdex() phase to clean up resources. We can get rid of this
15332        // if we move dex files under the common app path.
15333        /* nullable */ String[] instructionSets;
15334
15335        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15336                int installFlags, String installerPackageName, String volumeUuid,
15337                UserHandle user, String[] instructionSets,
15338                String abiOverride, String[] installGrantPermissions,
15339                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15340                int installReason) {
15341            this.origin = origin;
15342            this.move = move;
15343            this.installFlags = installFlags;
15344            this.observer = observer;
15345            this.installerPackageName = installerPackageName;
15346            this.volumeUuid = volumeUuid;
15347            this.user = user;
15348            this.instructionSets = instructionSets;
15349            this.abiOverride = abiOverride;
15350            this.installGrantPermissions = installGrantPermissions;
15351            this.traceMethod = traceMethod;
15352            this.traceCookie = traceCookie;
15353            this.signingDetails = signingDetails;
15354            this.installReason = installReason;
15355        }
15356
15357        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15358        abstract int doPreInstall(int status);
15359
15360        /**
15361         * Rename package into final resting place. All paths on the given
15362         * scanned package should be updated to reflect the rename.
15363         */
15364        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15365        abstract int doPostInstall(int status, int uid);
15366
15367        /** @see PackageSettingBase#codePathString */
15368        abstract String getCodePath();
15369        /** @see PackageSettingBase#resourcePathString */
15370        abstract String getResourcePath();
15371
15372        // Need installer lock especially for dex file removal.
15373        abstract void cleanUpResourcesLI();
15374        abstract boolean doPostDeleteLI(boolean delete);
15375
15376        /**
15377         * Called before the source arguments are copied. This is used mostly
15378         * for MoveParams when it needs to read the source file to put it in the
15379         * destination.
15380         */
15381        int doPreCopy() {
15382            return PackageManager.INSTALL_SUCCEEDED;
15383        }
15384
15385        /**
15386         * Called after the source arguments are copied. This is used mostly for
15387         * MoveParams when it needs to read the source file to put it in the
15388         * destination.
15389         */
15390        int doPostCopy(int uid) {
15391            return PackageManager.INSTALL_SUCCEEDED;
15392        }
15393
15394        protected boolean isFwdLocked() {
15395            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15396        }
15397
15398        protected boolean isExternalAsec() {
15399            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15400        }
15401
15402        protected boolean isEphemeral() {
15403            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15404        }
15405
15406        UserHandle getUser() {
15407            return user;
15408        }
15409    }
15410
15411    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15412        if (!allCodePaths.isEmpty()) {
15413            if (instructionSets == null) {
15414                throw new IllegalStateException("instructionSet == null");
15415            }
15416            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15417            for (String codePath : allCodePaths) {
15418                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15419                    try {
15420                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15421                    } catch (InstallerException ignored) {
15422                    }
15423                }
15424            }
15425        }
15426    }
15427
15428    /**
15429     * Logic to handle installation of non-ASEC applications, including copying
15430     * and renaming logic.
15431     */
15432    class FileInstallArgs extends InstallArgs {
15433        private File codeFile;
15434        private File resourceFile;
15435
15436        // Example topology:
15437        // /data/app/com.example/base.apk
15438        // /data/app/com.example/split_foo.apk
15439        // /data/app/com.example/lib/arm/libfoo.so
15440        // /data/app/com.example/lib/arm64/libfoo.so
15441        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15442
15443        /** New install */
15444        FileInstallArgs(InstallParams params) {
15445            super(params.origin, params.move, params.observer, params.installFlags,
15446                    params.installerPackageName, params.volumeUuid,
15447                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15448                    params.grantedRuntimePermissions,
15449                    params.traceMethod, params.traceCookie, params.signingDetails,
15450                    params.installReason);
15451            if (isFwdLocked()) {
15452                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15453            }
15454        }
15455
15456        /** Existing install */
15457        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15458            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15459                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15460                    PackageManager.INSTALL_REASON_UNKNOWN);
15461            this.codeFile = (codePath != null) ? new File(codePath) : null;
15462            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15463        }
15464
15465        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15466            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15467            try {
15468                return doCopyApk(imcs, temp);
15469            } finally {
15470                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15471            }
15472        }
15473
15474        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15475            if (origin.staged) {
15476                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15477                codeFile = origin.file;
15478                resourceFile = origin.file;
15479                return PackageManager.INSTALL_SUCCEEDED;
15480            }
15481
15482            try {
15483                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15484                final File tempDir =
15485                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15486                codeFile = tempDir;
15487                resourceFile = tempDir;
15488            } catch (IOException e) {
15489                Slog.w(TAG, "Failed to create copy file: " + e);
15490                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15491            }
15492
15493            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15494                @Override
15495                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15496                    if (!FileUtils.isValidExtFilename(name)) {
15497                        throw new IllegalArgumentException("Invalid filename: " + name);
15498                    }
15499                    try {
15500                        final File file = new File(codeFile, name);
15501                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15502                                O_RDWR | O_CREAT, 0644);
15503                        Os.chmod(file.getAbsolutePath(), 0644);
15504                        return new ParcelFileDescriptor(fd);
15505                    } catch (ErrnoException e) {
15506                        throw new RemoteException("Failed to open: " + e.getMessage());
15507                    }
15508                }
15509            };
15510
15511            int ret = PackageManager.INSTALL_SUCCEEDED;
15512            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15513            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15514                Slog.e(TAG, "Failed to copy package");
15515                return ret;
15516            }
15517
15518            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15519            NativeLibraryHelper.Handle handle = null;
15520            try {
15521                handle = NativeLibraryHelper.Handle.create(codeFile);
15522                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15523                        abiOverride);
15524            } catch (IOException e) {
15525                Slog.e(TAG, "Copying native libraries failed", e);
15526                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15527            } finally {
15528                IoUtils.closeQuietly(handle);
15529            }
15530
15531            return ret;
15532        }
15533
15534        int doPreInstall(int status) {
15535            if (status != PackageManager.INSTALL_SUCCEEDED) {
15536                cleanUp();
15537            }
15538            return status;
15539        }
15540
15541        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15542            if (status != PackageManager.INSTALL_SUCCEEDED) {
15543                cleanUp();
15544                return false;
15545            }
15546
15547            final File targetDir = codeFile.getParentFile();
15548            final File beforeCodeFile = codeFile;
15549            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15550
15551            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15552            try {
15553                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15554            } catch (ErrnoException e) {
15555                Slog.w(TAG, "Failed to rename", e);
15556                return false;
15557            }
15558
15559            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15560                Slog.w(TAG, "Failed to restorecon");
15561                return false;
15562            }
15563
15564            // Reflect the rename internally
15565            codeFile = afterCodeFile;
15566            resourceFile = afterCodeFile;
15567
15568            // Reflect the rename in scanned details
15569            try {
15570                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15571            } catch (IOException e) {
15572                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15573                return false;
15574            }
15575            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15576                    afterCodeFile, pkg.baseCodePath));
15577            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15578                    afterCodeFile, pkg.splitCodePaths));
15579
15580            // Reflect the rename in app info
15581            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15582            pkg.setApplicationInfoCodePath(pkg.codePath);
15583            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15584            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15585            pkg.setApplicationInfoResourcePath(pkg.codePath);
15586            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15587            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15588
15589            return true;
15590        }
15591
15592        int doPostInstall(int status, int uid) {
15593            if (status != PackageManager.INSTALL_SUCCEEDED) {
15594                cleanUp();
15595            }
15596            return status;
15597        }
15598
15599        @Override
15600        String getCodePath() {
15601            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15602        }
15603
15604        @Override
15605        String getResourcePath() {
15606            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15607        }
15608
15609        private boolean cleanUp() {
15610            if (codeFile == null || !codeFile.exists()) {
15611                return false;
15612            }
15613
15614            removeCodePathLI(codeFile);
15615
15616            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15617                resourceFile.delete();
15618            }
15619
15620            return true;
15621        }
15622
15623        void cleanUpResourcesLI() {
15624            // Try enumerating all code paths before deleting
15625            List<String> allCodePaths = Collections.EMPTY_LIST;
15626            if (codeFile != null && codeFile.exists()) {
15627                try {
15628                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15629                    allCodePaths = pkg.getAllCodePaths();
15630                } catch (PackageParserException e) {
15631                    // Ignored; we tried our best
15632                }
15633            }
15634
15635            cleanUp();
15636            removeDexFiles(allCodePaths, instructionSets);
15637        }
15638
15639        boolean doPostDeleteLI(boolean delete) {
15640            // XXX err, shouldn't we respect the delete flag?
15641            cleanUpResourcesLI();
15642            return true;
15643        }
15644    }
15645
15646    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15647            PackageManagerException {
15648        if (copyRet < 0) {
15649            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15650                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15651                throw new PackageManagerException(copyRet, message);
15652            }
15653        }
15654    }
15655
15656    /**
15657     * Extract the StorageManagerService "container ID" from the full code path of an
15658     * .apk.
15659     */
15660    static String cidFromCodePath(String fullCodePath) {
15661        int eidx = fullCodePath.lastIndexOf("/");
15662        String subStr1 = fullCodePath.substring(0, eidx);
15663        int sidx = subStr1.lastIndexOf("/");
15664        return subStr1.substring(sidx+1, eidx);
15665    }
15666
15667    /**
15668     * Logic to handle movement of existing installed applications.
15669     */
15670    class MoveInstallArgs extends InstallArgs {
15671        private File codeFile;
15672        private File resourceFile;
15673
15674        /** New install */
15675        MoveInstallArgs(InstallParams params) {
15676            super(params.origin, params.move, params.observer, params.installFlags,
15677                    params.installerPackageName, params.volumeUuid,
15678                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15679                    params.grantedRuntimePermissions,
15680                    params.traceMethod, params.traceCookie, params.signingDetails,
15681                    params.installReason);
15682        }
15683
15684        int copyApk(IMediaContainerService imcs, boolean temp) {
15685            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15686                    + move.fromUuid + " to " + move.toUuid);
15687            synchronized (mInstaller) {
15688                try {
15689                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15690                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15691                } catch (InstallerException e) {
15692                    Slog.w(TAG, "Failed to move app", e);
15693                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15694                }
15695            }
15696
15697            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15698            resourceFile = codeFile;
15699            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15700
15701            return PackageManager.INSTALL_SUCCEEDED;
15702        }
15703
15704        int doPreInstall(int status) {
15705            if (status != PackageManager.INSTALL_SUCCEEDED) {
15706                cleanUp(move.toUuid);
15707            }
15708            return status;
15709        }
15710
15711        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15712            if (status != PackageManager.INSTALL_SUCCEEDED) {
15713                cleanUp(move.toUuid);
15714                return false;
15715            }
15716
15717            // Reflect the move in app info
15718            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15719            pkg.setApplicationInfoCodePath(pkg.codePath);
15720            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15721            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15722            pkg.setApplicationInfoResourcePath(pkg.codePath);
15723            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15724            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15725
15726            return true;
15727        }
15728
15729        int doPostInstall(int status, int uid) {
15730            if (status == PackageManager.INSTALL_SUCCEEDED) {
15731                cleanUp(move.fromUuid);
15732            } else {
15733                cleanUp(move.toUuid);
15734            }
15735            return status;
15736        }
15737
15738        @Override
15739        String getCodePath() {
15740            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15741        }
15742
15743        @Override
15744        String getResourcePath() {
15745            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15746        }
15747
15748        private boolean cleanUp(String volumeUuid) {
15749            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15750                    move.dataAppName);
15751            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15752            final int[] userIds = sUserManager.getUserIds();
15753            synchronized (mInstallLock) {
15754                // Clean up both app data and code
15755                // All package moves are frozen until finished
15756                for (int userId : userIds) {
15757                    try {
15758                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15759                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15760                    } catch (InstallerException e) {
15761                        Slog.w(TAG, String.valueOf(e));
15762                    }
15763                }
15764                removeCodePathLI(codeFile);
15765            }
15766            return true;
15767        }
15768
15769        void cleanUpResourcesLI() {
15770            throw new UnsupportedOperationException();
15771        }
15772
15773        boolean doPostDeleteLI(boolean delete) {
15774            throw new UnsupportedOperationException();
15775        }
15776    }
15777
15778    static String getAsecPackageName(String packageCid) {
15779        int idx = packageCid.lastIndexOf("-");
15780        if (idx == -1) {
15781            return packageCid;
15782        }
15783        return packageCid.substring(0, idx);
15784    }
15785
15786    // Utility method used to create code paths based on package name and available index.
15787    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15788        String idxStr = "";
15789        int idx = 1;
15790        // Fall back to default value of idx=1 if prefix is not
15791        // part of oldCodePath
15792        if (oldCodePath != null) {
15793            String subStr = oldCodePath;
15794            // Drop the suffix right away
15795            if (suffix != null && subStr.endsWith(suffix)) {
15796                subStr = subStr.substring(0, subStr.length() - suffix.length());
15797            }
15798            // If oldCodePath already contains prefix find out the
15799            // ending index to either increment or decrement.
15800            int sidx = subStr.lastIndexOf(prefix);
15801            if (sidx != -1) {
15802                subStr = subStr.substring(sidx + prefix.length());
15803                if (subStr != null) {
15804                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15805                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15806                    }
15807                    try {
15808                        idx = Integer.parseInt(subStr);
15809                        if (idx <= 1) {
15810                            idx++;
15811                        } else {
15812                            idx--;
15813                        }
15814                    } catch(NumberFormatException e) {
15815                    }
15816                }
15817            }
15818        }
15819        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15820        return prefix + idxStr;
15821    }
15822
15823    private File getNextCodePath(File targetDir, String packageName) {
15824        File result;
15825        SecureRandom random = new SecureRandom();
15826        byte[] bytes = new byte[16];
15827        do {
15828            random.nextBytes(bytes);
15829            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15830            result = new File(targetDir, packageName + "-" + suffix);
15831        } while (result.exists());
15832        return result;
15833    }
15834
15835    // Utility method that returns the relative package path with respect
15836    // to the installation directory. Like say for /data/data/com.test-1.apk
15837    // string com.test-1 is returned.
15838    static String deriveCodePathName(String codePath) {
15839        if (codePath == null) {
15840            return null;
15841        }
15842        final File codeFile = new File(codePath);
15843        final String name = codeFile.getName();
15844        if (codeFile.isDirectory()) {
15845            return name;
15846        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15847            final int lastDot = name.lastIndexOf('.');
15848            return name.substring(0, lastDot);
15849        } else {
15850            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15851            return null;
15852        }
15853    }
15854
15855    static class PackageInstalledInfo {
15856        String name;
15857        int uid;
15858        // The set of users that originally had this package installed.
15859        int[] origUsers;
15860        // The set of users that now have this package installed.
15861        int[] newUsers;
15862        PackageParser.Package pkg;
15863        int returnCode;
15864        String returnMsg;
15865        String installerPackageName;
15866        PackageRemovedInfo removedInfo;
15867        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15868
15869        public void setError(int code, String msg) {
15870            setReturnCode(code);
15871            setReturnMessage(msg);
15872            Slog.w(TAG, msg);
15873        }
15874
15875        public void setError(String msg, PackageParserException e) {
15876            setReturnCode(e.error);
15877            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15878            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15879            for (int i = 0; i < childCount; i++) {
15880                addedChildPackages.valueAt(i).setError(msg, e);
15881            }
15882            Slog.w(TAG, msg, e);
15883        }
15884
15885        public void setError(String msg, PackageManagerException e) {
15886            returnCode = e.error;
15887            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15888            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15889            for (int i = 0; i < childCount; i++) {
15890                addedChildPackages.valueAt(i).setError(msg, e);
15891            }
15892            Slog.w(TAG, msg, e);
15893        }
15894
15895        public void setReturnCode(int returnCode) {
15896            this.returnCode = returnCode;
15897            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15898            for (int i = 0; i < childCount; i++) {
15899                addedChildPackages.valueAt(i).returnCode = returnCode;
15900            }
15901        }
15902
15903        private void setReturnMessage(String returnMsg) {
15904            this.returnMsg = returnMsg;
15905            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15906            for (int i = 0; i < childCount; i++) {
15907                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15908            }
15909        }
15910
15911        // In some error cases we want to convey more info back to the observer
15912        String origPackage;
15913        String origPermission;
15914    }
15915
15916    /*
15917     * Install a non-existing package.
15918     */
15919    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15920            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15921            String volumeUuid, PackageInstalledInfo res, int installReason) {
15922        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15923
15924        // Remember this for later, in case we need to rollback this install
15925        String pkgName = pkg.packageName;
15926
15927        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15928
15929        synchronized(mPackages) {
15930            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15931            if (renamedPackage != null) {
15932                // A package with the same name is already installed, though
15933                // it has been renamed to an older name.  The package we
15934                // are trying to install should be installed as an update to
15935                // the existing one, but that has not been requested, so bail.
15936                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15937                        + " without first uninstalling package running as "
15938                        + renamedPackage);
15939                return;
15940            }
15941            if (mPackages.containsKey(pkgName)) {
15942                // Don't allow installation over an existing package with the same name.
15943                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15944                        + " without first uninstalling.");
15945                return;
15946            }
15947        }
15948
15949        try {
15950            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15951                    System.currentTimeMillis(), user);
15952
15953            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15954
15955            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15956                prepareAppDataAfterInstallLIF(newPackage);
15957
15958            } else {
15959                // Remove package from internal structures, but keep around any
15960                // data that might have already existed
15961                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15962                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15963            }
15964        } catch (PackageManagerException e) {
15965            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15966        }
15967
15968        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15969    }
15970
15971    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15972        try (DigestInputStream digestStream =
15973                new DigestInputStream(new FileInputStream(file), digest)) {
15974            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15975        }
15976    }
15977
15978    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15979            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15980            PackageInstalledInfo res, int installReason) {
15981        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15982
15983        final PackageParser.Package oldPackage;
15984        final PackageSetting ps;
15985        final String pkgName = pkg.packageName;
15986        final int[] allUsers;
15987        final int[] installedUsers;
15988
15989        synchronized(mPackages) {
15990            oldPackage = mPackages.get(pkgName);
15991            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15992
15993            // don't allow upgrade to target a release SDK from a pre-release SDK
15994            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15995                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15996            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15997                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15998            if (oldTargetsPreRelease
15999                    && !newTargetsPreRelease
16000                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16001                Slog.w(TAG, "Can't install package targeting released sdk");
16002                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16003                return;
16004            }
16005
16006            ps = mSettings.mPackages.get(pkgName);
16007
16008            // verify signatures are valid
16009            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16010            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16011                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16012                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16013                            "New package not signed by keys specified by upgrade-keysets: "
16014                                    + pkgName);
16015                    return;
16016                }
16017            } else {
16018
16019                // default to original signature matching
16020                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16021                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16022                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16023                            "New package has a different signature: " + pkgName);
16024                    return;
16025                }
16026            }
16027
16028            // don't allow a system upgrade unless the upgrade hash matches
16029            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16030                byte[] digestBytes = null;
16031                try {
16032                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16033                    updateDigest(digest, new File(pkg.baseCodePath));
16034                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16035                        for (String path : pkg.splitCodePaths) {
16036                            updateDigest(digest, new File(path));
16037                        }
16038                    }
16039                    digestBytes = digest.digest();
16040                } catch (NoSuchAlgorithmException | IOException e) {
16041                    res.setError(INSTALL_FAILED_INVALID_APK,
16042                            "Could not compute hash: " + pkgName);
16043                    return;
16044                }
16045                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16046                    res.setError(INSTALL_FAILED_INVALID_APK,
16047                            "New package fails restrict-update check: " + pkgName);
16048                    return;
16049                }
16050                // retain upgrade restriction
16051                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16052            }
16053
16054            // Check for shared user id changes
16055            String invalidPackageName =
16056                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16057            if (invalidPackageName != null) {
16058                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16059                        "Package " + invalidPackageName + " tried to change user "
16060                                + oldPackage.mSharedUserId);
16061                return;
16062            }
16063
16064            // check if the new package supports all of the abis which the old package supports
16065            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16066            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16067            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16068                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16069                        "Update to package " + pkgName + " doesn't support multi arch");
16070                return;
16071            }
16072
16073            // In case of rollback, remember per-user/profile install state
16074            allUsers = sUserManager.getUserIds();
16075            installedUsers = ps.queryInstalledUsers(allUsers, true);
16076
16077            // don't allow an upgrade from full to ephemeral
16078            if (isInstantApp) {
16079                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16080                    for (int currentUser : allUsers) {
16081                        if (!ps.getInstantApp(currentUser)) {
16082                            // can't downgrade from full to instant
16083                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16084                                    + " for user: " + currentUser);
16085                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16086                            return;
16087                        }
16088                    }
16089                } else if (!ps.getInstantApp(user.getIdentifier())) {
16090                    // can't downgrade from full to instant
16091                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16092                            + " for user: " + user.getIdentifier());
16093                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16094                    return;
16095                }
16096            }
16097        }
16098
16099        // Update what is removed
16100        res.removedInfo = new PackageRemovedInfo(this);
16101        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16102        res.removedInfo.removedPackage = oldPackage.packageName;
16103        res.removedInfo.installerPackageName = ps.installerPackageName;
16104        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16105        res.removedInfo.isUpdate = true;
16106        res.removedInfo.origUsers = installedUsers;
16107        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16108        for (int i = 0; i < installedUsers.length; i++) {
16109            final int userId = installedUsers[i];
16110            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16111        }
16112
16113        final int childCount = (oldPackage.childPackages != null)
16114                ? oldPackage.childPackages.size() : 0;
16115        for (int i = 0; i < childCount; i++) {
16116            boolean childPackageUpdated = false;
16117            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16118            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16119            if (res.addedChildPackages != null) {
16120                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16121                if (childRes != null) {
16122                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16123                    childRes.removedInfo.removedPackage = childPkg.packageName;
16124                    if (childPs != null) {
16125                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16126                    }
16127                    childRes.removedInfo.isUpdate = true;
16128                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16129                    childPackageUpdated = true;
16130                }
16131            }
16132            if (!childPackageUpdated) {
16133                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16134                childRemovedRes.removedPackage = childPkg.packageName;
16135                if (childPs != null) {
16136                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16137                }
16138                childRemovedRes.isUpdate = false;
16139                childRemovedRes.dataRemoved = true;
16140                synchronized (mPackages) {
16141                    if (childPs != null) {
16142                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16143                    }
16144                }
16145                if (res.removedInfo.removedChildPackages == null) {
16146                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16147                }
16148                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16149            }
16150        }
16151
16152        boolean sysPkg = (isSystemApp(oldPackage));
16153        if (sysPkg) {
16154            // Set the system/privileged/oem/vendor/product flags as needed
16155            final boolean privileged =
16156                    (oldPackage.applicationInfo.privateFlags
16157                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16158            final boolean oem =
16159                    (oldPackage.applicationInfo.privateFlags
16160                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16161            final boolean vendor =
16162                    (oldPackage.applicationInfo.privateFlags
16163                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16164            final boolean product =
16165                    (oldPackage.applicationInfo.privateFlags
16166                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16167            final @ParseFlags int systemParseFlags = parseFlags;
16168            final @ScanFlags int systemScanFlags = scanFlags
16169                    | SCAN_AS_SYSTEM
16170                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16171                    | (oem ? SCAN_AS_OEM : 0)
16172                    | (vendor ? SCAN_AS_VENDOR : 0)
16173                    | (product ? SCAN_AS_PRODUCT : 0);
16174
16175            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16176                    user, allUsers, installerPackageName, res, installReason);
16177        } else {
16178            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16179                    user, allUsers, installerPackageName, res, installReason);
16180        }
16181    }
16182
16183    @Override
16184    public List<String> getPreviousCodePaths(String packageName) {
16185        final int callingUid = Binder.getCallingUid();
16186        final List<String> result = new ArrayList<>();
16187        if (getInstantAppPackageName(callingUid) != null) {
16188            return result;
16189        }
16190        final PackageSetting ps = mSettings.mPackages.get(packageName);
16191        if (ps != null
16192                && ps.oldCodePaths != null
16193                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16194            result.addAll(ps.oldCodePaths);
16195        }
16196        return result;
16197    }
16198
16199    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16200            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16201            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16202            String installerPackageName, PackageInstalledInfo res, int installReason) {
16203        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16204                + deletedPackage);
16205
16206        String pkgName = deletedPackage.packageName;
16207        boolean deletedPkg = true;
16208        boolean addedPkg = false;
16209        boolean updatedSettings = false;
16210        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16211        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16212                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16213
16214        final long origUpdateTime = (pkg.mExtras != null)
16215                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16216
16217        // First delete the existing package while retaining the data directory
16218        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16219                res.removedInfo, true, pkg)) {
16220            // If the existing package wasn't successfully deleted
16221            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16222            deletedPkg = false;
16223        } else {
16224            // Successfully deleted the old package; proceed with replace.
16225
16226            // If deleted package lived in a container, give users a chance to
16227            // relinquish resources before killing.
16228            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16229                if (DEBUG_INSTALL) {
16230                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16231                }
16232                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16233                final ArrayList<String> pkgList = new ArrayList<String>(1);
16234                pkgList.add(deletedPackage.applicationInfo.packageName);
16235                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16236            }
16237
16238            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16239                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16240
16241            try {
16242                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16243                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16244                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16245                        installReason);
16246
16247                // Update the in-memory copy of the previous code paths.
16248                PackageSetting ps = mSettings.mPackages.get(pkgName);
16249                if (!killApp) {
16250                    if (ps.oldCodePaths == null) {
16251                        ps.oldCodePaths = new ArraySet<>();
16252                    }
16253                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16254                    if (deletedPackage.splitCodePaths != null) {
16255                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16256                    }
16257                } else {
16258                    ps.oldCodePaths = null;
16259                }
16260                if (ps.childPackageNames != null) {
16261                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16262                        final String childPkgName = ps.childPackageNames.get(i);
16263                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16264                        childPs.oldCodePaths = ps.oldCodePaths;
16265                    }
16266                }
16267                // set instant app status, but, only if it's explicitly specified
16268                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16269                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16270                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16271                prepareAppDataAfterInstallLIF(newPackage);
16272                addedPkg = true;
16273                mDexManager.notifyPackageUpdated(newPackage.packageName,
16274                        newPackage.baseCodePath, newPackage.splitCodePaths);
16275            } catch (PackageManagerException e) {
16276                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16277            }
16278        }
16279
16280        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16281            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16282
16283            // Revert all internal state mutations and added folders for the failed install
16284            if (addedPkg) {
16285                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16286                        res.removedInfo, true, null);
16287            }
16288
16289            // Restore the old package
16290            if (deletedPkg) {
16291                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16292                File restoreFile = new File(deletedPackage.codePath);
16293                // Parse old package
16294                boolean oldExternal = isExternal(deletedPackage);
16295                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16296                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16297                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16298                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16299                try {
16300                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16301                            null);
16302                } catch (PackageManagerException e) {
16303                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16304                            + e.getMessage());
16305                    return;
16306                }
16307
16308                synchronized (mPackages) {
16309                    // Ensure the installer package name up to date
16310                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16311
16312                    // Update permissions for restored package
16313                    mPermissionManager.updatePermissions(
16314                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16315                            mPermissionCallback);
16316
16317                    mSettings.writeLPr();
16318                }
16319
16320                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16321            }
16322        } else {
16323            synchronized (mPackages) {
16324                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16325                if (ps != null) {
16326                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16327                    if (res.removedInfo.removedChildPackages != null) {
16328                        final int childCount = res.removedInfo.removedChildPackages.size();
16329                        // Iterate in reverse as we may modify the collection
16330                        for (int i = childCount - 1; i >= 0; i--) {
16331                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16332                            if (res.addedChildPackages.containsKey(childPackageName)) {
16333                                res.removedInfo.removedChildPackages.removeAt(i);
16334                            } else {
16335                                PackageRemovedInfo childInfo = res.removedInfo
16336                                        .removedChildPackages.valueAt(i);
16337                                childInfo.removedForAllUsers = mPackages.get(
16338                                        childInfo.removedPackage) == null;
16339                            }
16340                        }
16341                    }
16342                }
16343            }
16344        }
16345    }
16346
16347    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16348            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16349            final @ScanFlags int scanFlags, UserHandle user,
16350            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16351            int installReason) {
16352        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16353                + ", old=" + deletedPackage);
16354
16355        final boolean disabledSystem;
16356
16357        // Remove existing system package
16358        removePackageLI(deletedPackage, true);
16359
16360        synchronized (mPackages) {
16361            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16362        }
16363        if (!disabledSystem) {
16364            // We didn't need to disable the .apk as a current system package,
16365            // which means we are replacing another update that is already
16366            // installed.  We need to make sure to delete the older one's .apk.
16367            res.removedInfo.args = createInstallArgsForExisting(0,
16368                    deletedPackage.applicationInfo.getCodePath(),
16369                    deletedPackage.applicationInfo.getResourcePath(),
16370                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16371        } else {
16372            res.removedInfo.args = null;
16373        }
16374
16375        // Successfully disabled the old package. Now proceed with re-installation
16376        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16377                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16378
16379        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16380        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16381                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16382
16383        PackageParser.Package newPackage = null;
16384        try {
16385            // Add the package to the internal data structures
16386            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16387
16388            // Set the update and install times
16389            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16390            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16391                    System.currentTimeMillis());
16392
16393            // Update the package dynamic state if succeeded
16394            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16395                // Now that the install succeeded make sure we remove data
16396                // directories for any child package the update removed.
16397                final int deletedChildCount = (deletedPackage.childPackages != null)
16398                        ? deletedPackage.childPackages.size() : 0;
16399                final int newChildCount = (newPackage.childPackages != null)
16400                        ? newPackage.childPackages.size() : 0;
16401                for (int i = 0; i < deletedChildCount; i++) {
16402                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16403                    boolean childPackageDeleted = true;
16404                    for (int j = 0; j < newChildCount; j++) {
16405                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16406                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16407                            childPackageDeleted = false;
16408                            break;
16409                        }
16410                    }
16411                    if (childPackageDeleted) {
16412                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16413                                deletedChildPkg.packageName);
16414                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16415                            PackageRemovedInfo removedChildRes = res.removedInfo
16416                                    .removedChildPackages.get(deletedChildPkg.packageName);
16417                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16418                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16419                        }
16420                    }
16421                }
16422
16423                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16424                        installReason);
16425                prepareAppDataAfterInstallLIF(newPackage);
16426
16427                mDexManager.notifyPackageUpdated(newPackage.packageName,
16428                            newPackage.baseCodePath, newPackage.splitCodePaths);
16429            }
16430        } catch (PackageManagerException e) {
16431            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16432            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16433        }
16434
16435        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16436            // Re installation failed. Restore old information
16437            // Remove new pkg information
16438            if (newPackage != null) {
16439                removeInstalledPackageLI(newPackage, true);
16440            }
16441            // Add back the old system package
16442            try {
16443                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16444            } catch (PackageManagerException e) {
16445                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16446            }
16447
16448            synchronized (mPackages) {
16449                if (disabledSystem) {
16450                    enableSystemPackageLPw(deletedPackage);
16451                }
16452
16453                // Ensure the installer package name up to date
16454                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16455
16456                // Update permissions for restored package
16457                mPermissionManager.updatePermissions(
16458                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16459                        mPermissionCallback);
16460
16461                mSettings.writeLPr();
16462            }
16463
16464            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16465                    + " after failed upgrade");
16466        }
16467    }
16468
16469    /**
16470     * Checks whether the parent or any of the child packages have a change shared
16471     * user. For a package to be a valid update the shred users of the parent and
16472     * the children should match. We may later support changing child shared users.
16473     * @param oldPkg The updated package.
16474     * @param newPkg The update package.
16475     * @return The shared user that change between the versions.
16476     */
16477    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16478            PackageParser.Package newPkg) {
16479        // Check parent shared user
16480        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16481            return newPkg.packageName;
16482        }
16483        // Check child shared users
16484        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16485        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16486        for (int i = 0; i < newChildCount; i++) {
16487            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16488            // If this child was present, did it have the same shared user?
16489            for (int j = 0; j < oldChildCount; j++) {
16490                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16491                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16492                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16493                    return newChildPkg.packageName;
16494                }
16495            }
16496        }
16497        return null;
16498    }
16499
16500    private void removeNativeBinariesLI(PackageSetting ps) {
16501        // Remove the lib path for the parent package
16502        if (ps != null) {
16503            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16504            // Remove the lib path for the child packages
16505            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16506            for (int i = 0; i < childCount; i++) {
16507                PackageSetting childPs = null;
16508                synchronized (mPackages) {
16509                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16510                }
16511                if (childPs != null) {
16512                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16513                            .legacyNativeLibraryPathString);
16514                }
16515            }
16516        }
16517    }
16518
16519    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16520        // Enable the parent package
16521        mSettings.enableSystemPackageLPw(pkg.packageName);
16522        // Enable the child packages
16523        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16524        for (int i = 0; i < childCount; i++) {
16525            PackageParser.Package childPkg = pkg.childPackages.get(i);
16526            mSettings.enableSystemPackageLPw(childPkg.packageName);
16527        }
16528    }
16529
16530    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16531            PackageParser.Package newPkg) {
16532        // Disable the parent package (parent always replaced)
16533        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16534        // Disable the child packages
16535        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16536        for (int i = 0; i < childCount; i++) {
16537            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16538            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16539            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16540        }
16541        return disabled;
16542    }
16543
16544    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16545            String installerPackageName) {
16546        // Enable the parent package
16547        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16548        // Enable the child packages
16549        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16550        for (int i = 0; i < childCount; i++) {
16551            PackageParser.Package childPkg = pkg.childPackages.get(i);
16552            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16553        }
16554    }
16555
16556    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16557            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16558        // Update the parent package setting
16559        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16560                res, user, installReason);
16561        // Update the child packages setting
16562        final int childCount = (newPackage.childPackages != null)
16563                ? newPackage.childPackages.size() : 0;
16564        for (int i = 0; i < childCount; i++) {
16565            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16566            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16567            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16568                    childRes.origUsers, childRes, user, installReason);
16569        }
16570    }
16571
16572    private void updateSettingsInternalLI(PackageParser.Package pkg,
16573            String installerPackageName, int[] allUsers, int[] installedForUsers,
16574            PackageInstalledInfo res, UserHandle user, int installReason) {
16575        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16576
16577        String pkgName = pkg.packageName;
16578        synchronized (mPackages) {
16579            //write settings. the installStatus will be incomplete at this stage.
16580            //note that the new package setting would have already been
16581            //added to mPackages. It hasn't been persisted yet.
16582            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16583            // TODO: Remove this write? It's also written at the end of this method
16584            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16585            mSettings.writeLPr();
16586            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16587        }
16588
16589        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16590        synchronized (mPackages) {
16591// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16592            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16593                    mPermissionCallback);
16594            // For system-bundled packages, we assume that installing an upgraded version
16595            // of the package implies that the user actually wants to run that new code,
16596            // so we enable the package.
16597            PackageSetting ps = mSettings.mPackages.get(pkgName);
16598            final int userId = user.getIdentifier();
16599            if (ps != null) {
16600                if (isSystemApp(pkg)) {
16601                    if (DEBUG_INSTALL) {
16602                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16603                    }
16604                    // Enable system package for requested users
16605                    if (res.origUsers != null) {
16606                        for (int origUserId : res.origUsers) {
16607                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16608                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16609                                        origUserId, installerPackageName);
16610                            }
16611                        }
16612                    }
16613                    // Also convey the prior install/uninstall state
16614                    if (allUsers != null && installedForUsers != null) {
16615                        for (int currentUserId : allUsers) {
16616                            final boolean installed = ArrayUtils.contains(
16617                                    installedForUsers, currentUserId);
16618                            if (DEBUG_INSTALL) {
16619                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16620                            }
16621                            ps.setInstalled(installed, currentUserId);
16622                        }
16623                        // these install state changes will be persisted in the
16624                        // upcoming call to mSettings.writeLPr().
16625                    }
16626                }
16627                // It's implied that when a user requests installation, they want the app to be
16628                // installed and enabled.
16629                if (userId != UserHandle.USER_ALL) {
16630                    ps.setInstalled(true, userId);
16631                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16632                } else {
16633                    for (int currentUserId : sUserManager.getUserIds()) {
16634                        ps.setInstalled(true, currentUserId);
16635                        ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId,
16636                                installerPackageName);
16637                    }
16638                }
16639
16640                // When replacing an existing package, preserve the original install reason for all
16641                // users that had the package installed before.
16642                final Set<Integer> previousUserIds = new ArraySet<>();
16643                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16644                    final int installReasonCount = res.removedInfo.installReasons.size();
16645                    for (int i = 0; i < installReasonCount; i++) {
16646                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16647                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16648                        ps.setInstallReason(previousInstallReason, previousUserId);
16649                        previousUserIds.add(previousUserId);
16650                    }
16651                }
16652
16653                // Set install reason for users that are having the package newly installed.
16654                if (userId == UserHandle.USER_ALL) {
16655                    for (int currentUserId : sUserManager.getUserIds()) {
16656                        if (!previousUserIds.contains(currentUserId)) {
16657                            ps.setInstallReason(installReason, currentUserId);
16658                        }
16659                    }
16660                } else if (!previousUserIds.contains(userId)) {
16661                    ps.setInstallReason(installReason, userId);
16662                }
16663                mSettings.writeKernelMappingLPr(ps);
16664            }
16665            res.name = pkgName;
16666            res.uid = pkg.applicationInfo.uid;
16667            res.pkg = pkg;
16668            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16669            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16670            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16671            //to update install status
16672            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16673            mSettings.writeLPr();
16674            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16675        }
16676
16677        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16678    }
16679
16680    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16681        try {
16682            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16683            installPackageLI(args, res);
16684        } finally {
16685            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16686        }
16687    }
16688
16689    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16690        final int installFlags = args.installFlags;
16691        final String installerPackageName = args.installerPackageName;
16692        final String volumeUuid = args.volumeUuid;
16693        final File tmpPackageFile = new File(args.getCodePath());
16694        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16695        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16696                || (args.volumeUuid != null));
16697        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16698        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16699        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16700        final boolean virtualPreload =
16701                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16702        boolean replace = false;
16703        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16704        if (args.move != null) {
16705            // moving a complete application; perform an initial scan on the new install location
16706            scanFlags |= SCAN_INITIAL;
16707        }
16708        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16709            scanFlags |= SCAN_DONT_KILL_APP;
16710        }
16711        if (instantApp) {
16712            scanFlags |= SCAN_AS_INSTANT_APP;
16713        }
16714        if (fullApp) {
16715            scanFlags |= SCAN_AS_FULL_APP;
16716        }
16717        if (virtualPreload) {
16718            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16719        }
16720
16721        // Result object to be returned
16722        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16723        res.installerPackageName = installerPackageName;
16724
16725        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16726
16727        // Sanity check
16728        if (instantApp && (forwardLocked || onExternal)) {
16729            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16730                    + " external=" + onExternal);
16731            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16732            return;
16733        }
16734
16735        // Retrieve PackageSettings and parse package
16736        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16737                | PackageParser.PARSE_ENFORCE_CODE
16738                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16739                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16740                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16741        PackageParser pp = new PackageParser();
16742        pp.setSeparateProcesses(mSeparateProcesses);
16743        pp.setDisplayMetrics(mMetrics);
16744        pp.setCallback(mPackageParserCallback);
16745
16746        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16747        final PackageParser.Package pkg;
16748        try {
16749            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16750            DexMetadataHelper.validatePackageDexMetadata(pkg);
16751        } catch (PackageParserException e) {
16752            res.setError("Failed parse during installPackageLI", e);
16753            return;
16754        } finally {
16755            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16756        }
16757
16758        // Instant apps have several additional install-time checks.
16759        if (instantApp) {
16760            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16761                Slog.w(TAG,
16762                        "Instant app package " + pkg.packageName + " does not target at least O");
16763                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16764                        "Instant app package must target at least O");
16765                return;
16766            }
16767            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16768                Slog.w(TAG, "Instant app package " + pkg.packageName
16769                        + " does not target targetSandboxVersion 2");
16770                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16771                        "Instant app package must use targetSandboxVersion 2");
16772                return;
16773            }
16774            if (pkg.mSharedUserId != null) {
16775                Slog.w(TAG, "Instant app package " + pkg.packageName
16776                        + " may not declare sharedUserId.");
16777                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16778                        "Instant app package may not declare a sharedUserId");
16779                return;
16780            }
16781        }
16782
16783        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16784            // Static shared libraries have synthetic package names
16785            renameStaticSharedLibraryPackage(pkg);
16786
16787            // No static shared libs on external storage
16788            if (onExternal) {
16789                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16790                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16791                        "Packages declaring static-shared libs cannot be updated");
16792                return;
16793            }
16794        }
16795
16796        // If we are installing a clustered package add results for the children
16797        if (pkg.childPackages != null) {
16798            synchronized (mPackages) {
16799                final int childCount = pkg.childPackages.size();
16800                for (int i = 0; i < childCount; i++) {
16801                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16802                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16803                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16804                    childRes.pkg = childPkg;
16805                    childRes.name = childPkg.packageName;
16806                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16807                    if (childPs != null) {
16808                        childRes.origUsers = childPs.queryInstalledUsers(
16809                                sUserManager.getUserIds(), true);
16810                    }
16811                    if ((mPackages.containsKey(childPkg.packageName))) {
16812                        childRes.removedInfo = new PackageRemovedInfo(this);
16813                        childRes.removedInfo.removedPackage = childPkg.packageName;
16814                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16815                    }
16816                    if (res.addedChildPackages == null) {
16817                        res.addedChildPackages = new ArrayMap<>();
16818                    }
16819                    res.addedChildPackages.put(childPkg.packageName, childRes);
16820                }
16821            }
16822        }
16823
16824        // If package doesn't declare API override, mark that we have an install
16825        // time CPU ABI override.
16826        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16827            pkg.cpuAbiOverride = args.abiOverride;
16828        }
16829
16830        String pkgName = res.name = pkg.packageName;
16831        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16832            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16833                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16834                return;
16835            }
16836        }
16837
16838        try {
16839            // either use what we've been given or parse directly from the APK
16840            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16841                pkg.setSigningDetails(args.signingDetails);
16842            } else {
16843                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16844            }
16845        } catch (PackageParserException e) {
16846            res.setError("Failed collect during installPackageLI", e);
16847            return;
16848        }
16849
16850        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16851                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16852            Slog.w(TAG, "Instant app package " + pkg.packageName
16853                    + " is not signed with at least APK Signature Scheme v2");
16854            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16855                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16856            return;
16857        }
16858
16859        // Get rid of all references to package scan path via parser.
16860        pp = null;
16861        String oldCodePath = null;
16862        boolean systemApp = false;
16863        synchronized (mPackages) {
16864            // Check if installing already existing package
16865            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16866                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16867                if (pkg.mOriginalPackages != null
16868                        && pkg.mOriginalPackages.contains(oldName)
16869                        && mPackages.containsKey(oldName)) {
16870                    // This package is derived from an original package,
16871                    // and this device has been updating from that original
16872                    // name.  We must continue using the original name, so
16873                    // rename the new package here.
16874                    pkg.setPackageName(oldName);
16875                    pkgName = pkg.packageName;
16876                    replace = true;
16877                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16878                            + oldName + " pkgName=" + pkgName);
16879                } else if (mPackages.containsKey(pkgName)) {
16880                    // This package, under its official name, already exists
16881                    // on the device; we should replace it.
16882                    replace = true;
16883                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16884                }
16885
16886                // Child packages are installed through the parent package
16887                if (pkg.parentPackage != null) {
16888                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16889                            "Package " + pkg.packageName + " is child of package "
16890                                    + pkg.parentPackage.parentPackage + ". Child packages "
16891                                    + "can be updated only through the parent package.");
16892                    return;
16893                }
16894
16895                if (replace) {
16896                    // Prevent apps opting out from runtime permissions
16897                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16898                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16899                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16900                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16901                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16902                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16903                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16904                                        + " doesn't support runtime permissions but the old"
16905                                        + " target SDK " + oldTargetSdk + " does.");
16906                        return;
16907                    }
16908                    // Prevent persistent apps from being updated
16909                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16910                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16911                                "Package " + oldPackage.packageName + " is a persistent app. "
16912                                        + "Persistent apps are not updateable.");
16913                        return;
16914                    }
16915                    // Prevent apps from downgrading their targetSandbox.
16916                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16917                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16918                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16919                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16920                                "Package " + pkg.packageName + " new target sandbox "
16921                                + newTargetSandbox + " is incompatible with the previous value of"
16922                                + oldTargetSandbox + ".");
16923                        return;
16924                    }
16925
16926                    // Prevent installing of child packages
16927                    if (oldPackage.parentPackage != null) {
16928                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16929                                "Package " + pkg.packageName + " is child of package "
16930                                        + oldPackage.parentPackage + ". Child packages "
16931                                        + "can be updated only through the parent package.");
16932                        return;
16933                    }
16934                }
16935            }
16936
16937            PackageSetting ps = mSettings.mPackages.get(pkgName);
16938            if (ps != null) {
16939                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16940
16941                // Static shared libs have same package with different versions where
16942                // we internally use a synthetic package name to allow multiple versions
16943                // of the same package, therefore we need to compare signatures against
16944                // the package setting for the latest library version.
16945                PackageSetting signatureCheckPs = ps;
16946                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16947                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16948                    if (libraryEntry != null) {
16949                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16950                    }
16951                }
16952
16953                // Quick sanity check that we're signed correctly if updating;
16954                // we'll check this again later when scanning, but we want to
16955                // bail early here before tripping over redefined permissions.
16956                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16957                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16958                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16959                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16960                                + pkg.packageName + " upgrade keys do not match the "
16961                                + "previously installed version");
16962                        return;
16963                    }
16964                } else {
16965                    try {
16966                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16967                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16968                        // We don't care about disabledPkgSetting on install for now.
16969                        final boolean compatMatch = verifySignatures(
16970                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
16971                                compareRecover);
16972                        // The new KeySets will be re-added later in the scanning process.
16973                        if (compatMatch) {
16974                            synchronized (mPackages) {
16975                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16976                            }
16977                        }
16978                    } catch (PackageManagerException e) {
16979                        res.setError(e.error, e.getMessage());
16980                        return;
16981                    }
16982                }
16983
16984                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16985                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16986                    systemApp = (ps.pkg.applicationInfo.flags &
16987                            ApplicationInfo.FLAG_SYSTEM) != 0;
16988                }
16989                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16990            }
16991
16992            int N = pkg.permissions.size();
16993            for (int i = N-1; i >= 0; i--) {
16994                final PackageParser.Permission perm = pkg.permissions.get(i);
16995                final BasePermission bp =
16996                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16997
16998                // Don't allow anyone but the system to define ephemeral permissions.
16999                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17000                        && !systemApp) {
17001                    Slog.w(TAG, "Non-System package " + pkg.packageName
17002                            + " attempting to delcare ephemeral permission "
17003                            + perm.info.name + "; Removing ephemeral.");
17004                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17005                }
17006
17007                // Check whether the newly-scanned package wants to define an already-defined perm
17008                if (bp != null) {
17009                    // If the defining package is signed with our cert, it's okay.  This
17010                    // also includes the "updating the same package" case, of course.
17011                    // "updating same package" could also involve key-rotation.
17012                    final boolean sigsOk;
17013                    final String sourcePackageName = bp.getSourcePackageName();
17014                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17015                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17016                    if (sourcePackageName.equals(pkg.packageName)
17017                            && (ksms.shouldCheckUpgradeKeySetLocked(
17018                                    sourcePackageSetting, scanFlags))) {
17019                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17020                    } else {
17021
17022                        // in the event of signing certificate rotation, we need to see if the
17023                        // package's certificate has rotated from the current one, or if it is an
17024                        // older certificate with which the current is ok with sharing permissions
17025                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17026                                        pkg.mSigningDetails,
17027                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17028                            sigsOk = true;
17029                        } else if (pkg.mSigningDetails.checkCapability(
17030                                        sourcePackageSetting.signatures.mSigningDetails,
17031                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17032
17033                            // the scanned package checks out, has signing certificate rotation
17034                            // history, and is newer; bring it over
17035                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17036                            sigsOk = true;
17037                        } else {
17038                            sigsOk = false;
17039                        }
17040                    }
17041                    if (!sigsOk) {
17042                        // If the owning package is the system itself, we log but allow
17043                        // install to proceed; we fail the install on all other permission
17044                        // redefinitions.
17045                        if (!sourcePackageName.equals("android")) {
17046                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17047                                    + pkg.packageName + " attempting to redeclare permission "
17048                                    + perm.info.name + " already owned by " + sourcePackageName);
17049                            res.origPermission = perm.info.name;
17050                            res.origPackage = sourcePackageName;
17051                            return;
17052                        } else {
17053                            Slog.w(TAG, "Package " + pkg.packageName
17054                                    + " attempting to redeclare system permission "
17055                                    + perm.info.name + "; ignoring new declaration");
17056                            pkg.permissions.remove(i);
17057                        }
17058                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17059                        // Prevent apps to change protection level to dangerous from any other
17060                        // type as this would allow a privilege escalation where an app adds a
17061                        // normal/signature permission in other app's group and later redefines
17062                        // it as dangerous leading to the group auto-grant.
17063                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17064                                == PermissionInfo.PROTECTION_DANGEROUS) {
17065                            if (bp != null && !bp.isRuntime()) {
17066                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17067                                        + "non-runtime permission " + perm.info.name
17068                                        + " to runtime; keeping old protection level");
17069                                perm.info.protectionLevel = bp.getProtectionLevel();
17070                            }
17071                        }
17072                    }
17073                }
17074            }
17075        }
17076
17077        if (systemApp) {
17078            if (onExternal) {
17079                // Abort update; system app can't be replaced with app on sdcard
17080                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17081                        "Cannot install updates to system apps on sdcard");
17082                return;
17083            } else if (instantApp) {
17084                // Abort update; system app can't be replaced with an instant app
17085                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17086                        "Cannot update a system app with an instant app");
17087                return;
17088            }
17089        }
17090
17091        if (args.move != null) {
17092            // We did an in-place move, so dex is ready to roll
17093            scanFlags |= SCAN_NO_DEX;
17094            scanFlags |= SCAN_MOVE;
17095
17096            synchronized (mPackages) {
17097                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17098                if (ps == null) {
17099                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17100                            "Missing settings for moved package " + pkgName);
17101                }
17102
17103                // We moved the entire application as-is, so bring over the
17104                // previously derived ABI information.
17105                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17106                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17107            }
17108
17109        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17110            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17111            scanFlags |= SCAN_NO_DEX;
17112
17113            try {
17114                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17115                    args.abiOverride : pkg.cpuAbiOverride);
17116                final boolean extractNativeLibs = !pkg.isLibrary();
17117                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17118            } catch (PackageManagerException pme) {
17119                Slog.e(TAG, "Error deriving application ABI", pme);
17120                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17121                return;
17122            }
17123
17124            // Shared libraries for the package need to be updated.
17125            synchronized (mPackages) {
17126                try {
17127                    updateSharedLibrariesLPr(pkg, null);
17128                } catch (PackageManagerException e) {
17129                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17130                }
17131            }
17132        }
17133
17134        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17135            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17136            return;
17137        }
17138
17139        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17140            String apkPath = null;
17141            synchronized (mPackages) {
17142                // Note that if the attacker managed to skip verify setup, for example by tampering
17143                // with the package settings, upon reboot we will do full apk verification when
17144                // verity is not detected.
17145                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17146                if (ps != null && ps.isPrivileged()) {
17147                    apkPath = pkg.baseCodePath;
17148                }
17149            }
17150
17151            if (apkPath != null) {
17152                final VerityUtils.SetupResult result =
17153                        VerityUtils.generateApkVeritySetupData(apkPath);
17154                if (result.isOk()) {
17155                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17156                    FileDescriptor fd = result.getUnownedFileDescriptor();
17157                    try {
17158                        mInstaller.installApkVerity(apkPath, fd);
17159                    } catch (InstallerException e) {
17160                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17161                                "Failed to set up verity: " + e);
17162                        return;
17163                    } finally {
17164                        IoUtils.closeQuietly(fd);
17165                    }
17166                } else if (result.isFailed()) {
17167                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17168                    return;
17169                } else {
17170                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17171                    // reboot.
17172                }
17173            }
17174        }
17175
17176        if (!instantApp) {
17177            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17178        } else {
17179            if (DEBUG_DOMAIN_VERIFICATION) {
17180                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17181            }
17182        }
17183
17184        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17185                "installPackageLI")) {
17186            if (replace) {
17187                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17188                    // Static libs have a synthetic package name containing the version
17189                    // and cannot be updated as an update would get a new package name,
17190                    // unless this is the exact same version code which is useful for
17191                    // development.
17192                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17193                    if (existingPkg != null &&
17194                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17195                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17196                                + "static-shared libs cannot be updated");
17197                        return;
17198                    }
17199                }
17200                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17201                        installerPackageName, res, args.installReason);
17202            } else {
17203                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17204                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17205            }
17206        }
17207
17208        // Prepare the application profiles for the new code paths.
17209        // This needs to be done before invoking dexopt so that any install-time profile
17210        // can be used for optimizations.
17211        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17212
17213        // Check whether we need to dexopt the app.
17214        //
17215        // NOTE: it is IMPORTANT to call dexopt:
17216        //   - after doRename which will sync the package data from PackageParser.Package and its
17217        //     corresponding ApplicationInfo.
17218        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17219        //     uid of the application (pkg.applicationInfo.uid).
17220        //     This update happens in place!
17221        //
17222        // We only need to dexopt if the package meets ALL of the following conditions:
17223        //   1) it is not forward locked.
17224        //   2) it is not on on an external ASEC container.
17225        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17226        //
17227        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17228        // complete, so we skip this step during installation. Instead, we'll take extra time
17229        // the first time the instant app starts. It's preferred to do it this way to provide
17230        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17231        // middle of running an instant app. The default behaviour can be overridden
17232        // via gservices.
17233        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17234                && !forwardLocked
17235                && !pkg.applicationInfo.isExternalAsec()
17236                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17237                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17238
17239        if (performDexopt) {
17240            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17241            // Do not run PackageDexOptimizer through the local performDexOpt
17242            // method because `pkg` may not be in `mPackages` yet.
17243            //
17244            // Also, don't fail application installs if the dexopt step fails.
17245            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17246                    REASON_INSTALL,
17247                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17248                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17249            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17250                    null /* instructionSets */,
17251                    getOrCreateCompilerPackageStats(pkg),
17252                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17253                    dexoptOptions);
17254            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17255        }
17256
17257        // Notify BackgroundDexOptService that the package has been changed.
17258        // If this is an update of a package which used to fail to compile,
17259        // BackgroundDexOptService will remove it from its blacklist.
17260        // TODO: Layering violation
17261        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17262
17263        synchronized (mPackages) {
17264            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17265            if (ps != null) {
17266                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17267                ps.setUpdateAvailable(false /*updateAvailable*/);
17268            }
17269
17270            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17271            for (int i = 0; i < childCount; i++) {
17272                PackageParser.Package childPkg = pkg.childPackages.get(i);
17273                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17274                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17275                if (childPs != null) {
17276                    childRes.newUsers = childPs.queryInstalledUsers(
17277                            sUserManager.getUserIds(), true);
17278                }
17279            }
17280
17281            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17282                updateSequenceNumberLP(ps, res.newUsers);
17283                updateInstantAppInstallerLocked(pkgName);
17284            }
17285        }
17286    }
17287
17288    private void startIntentFilterVerifications(int userId, boolean replacing,
17289            PackageParser.Package pkg) {
17290        if (mIntentFilterVerifierComponent == null) {
17291            Slog.w(TAG, "No IntentFilter verification will not be done as "
17292                    + "there is no IntentFilterVerifier available!");
17293            return;
17294        }
17295
17296        final int verifierUid = getPackageUid(
17297                mIntentFilterVerifierComponent.getPackageName(),
17298                MATCH_DEBUG_TRIAGED_MISSING,
17299                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17300
17301        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17302        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17303        mHandler.sendMessage(msg);
17304
17305        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17306        for (int i = 0; i < childCount; i++) {
17307            PackageParser.Package childPkg = pkg.childPackages.get(i);
17308            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17309            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17310            mHandler.sendMessage(msg);
17311        }
17312    }
17313
17314    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17315            PackageParser.Package pkg) {
17316        int size = pkg.activities.size();
17317        if (size == 0) {
17318            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17319                    "No activity, so no need to verify any IntentFilter!");
17320            return;
17321        }
17322
17323        final boolean hasDomainURLs = hasDomainURLs(pkg);
17324        if (!hasDomainURLs) {
17325            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17326                    "No domain URLs, so no need to verify any IntentFilter!");
17327            return;
17328        }
17329
17330        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17331                + " if any IntentFilter from the " + size
17332                + " Activities needs verification ...");
17333
17334        int count = 0;
17335        final String packageName = pkg.packageName;
17336
17337        synchronized (mPackages) {
17338            // If this is a new install and we see that we've already run verification for this
17339            // package, we have nothing to do: it means the state was restored from backup.
17340            if (!replacing) {
17341                IntentFilterVerificationInfo ivi =
17342                        mSettings.getIntentFilterVerificationLPr(packageName);
17343                if (ivi != null) {
17344                    if (DEBUG_DOMAIN_VERIFICATION) {
17345                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17346                                + ivi.getStatusString());
17347                    }
17348                    return;
17349                }
17350            }
17351
17352            // If any filters need to be verified, then all need to be.
17353            boolean needToVerify = false;
17354            for (PackageParser.Activity a : pkg.activities) {
17355                for (ActivityIntentInfo filter : a.intents) {
17356                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17357                        if (DEBUG_DOMAIN_VERIFICATION) {
17358                            Slog.d(TAG,
17359                                    "Intent filter needs verification, so processing all filters");
17360                        }
17361                        needToVerify = true;
17362                        break;
17363                    }
17364                }
17365            }
17366
17367            if (needToVerify) {
17368                final int verificationId = mIntentFilterVerificationToken++;
17369                for (PackageParser.Activity a : pkg.activities) {
17370                    for (ActivityIntentInfo filter : a.intents) {
17371                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17372                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17373                                    "Verification needed for IntentFilter:" + filter.toString());
17374                            mIntentFilterVerifier.addOneIntentFilterVerification(
17375                                    verifierUid, userId, verificationId, filter, packageName);
17376                            count++;
17377                        }
17378                    }
17379                }
17380            }
17381        }
17382
17383        if (count > 0) {
17384            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17385                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17386                    +  " for userId:" + userId);
17387            mIntentFilterVerifier.startVerifications(userId);
17388        } else {
17389            if (DEBUG_DOMAIN_VERIFICATION) {
17390                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17391            }
17392        }
17393    }
17394
17395    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17396        final ComponentName cn  = filter.activity.getComponentName();
17397        final String packageName = cn.getPackageName();
17398
17399        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17400                packageName);
17401        if (ivi == null) {
17402            return true;
17403        }
17404        int status = ivi.getStatus();
17405        switch (status) {
17406            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17407            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17408                return true;
17409
17410            default:
17411                // Nothing to do
17412                return false;
17413        }
17414    }
17415
17416    private static boolean isMultiArch(ApplicationInfo info) {
17417        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17418    }
17419
17420    private static boolean isExternal(PackageParser.Package pkg) {
17421        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17422    }
17423
17424    private static boolean isExternal(PackageSetting ps) {
17425        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17426    }
17427
17428    private static boolean isSystemApp(PackageParser.Package pkg) {
17429        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17430    }
17431
17432    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17433        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17434    }
17435
17436    private static boolean isOemApp(PackageParser.Package pkg) {
17437        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17438    }
17439
17440    private static boolean isVendorApp(PackageParser.Package pkg) {
17441        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17442    }
17443
17444    private static boolean isProductApp(PackageParser.Package pkg) {
17445        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17446    }
17447
17448    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17449        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17450    }
17451
17452    private static boolean isSystemApp(PackageSetting ps) {
17453        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17454    }
17455
17456    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17457        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17458    }
17459
17460    private int packageFlagsToInstallFlags(PackageSetting ps) {
17461        int installFlags = 0;
17462        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17463            // This existing package was an external ASEC install when we have
17464            // the external flag without a UUID
17465            installFlags |= PackageManager.INSTALL_EXTERNAL;
17466        }
17467        if (ps.isForwardLocked()) {
17468            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17469        }
17470        return installFlags;
17471    }
17472
17473    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17474        if (isExternal(pkg)) {
17475            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17476                return mSettings.getExternalVersion();
17477            } else {
17478                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17479            }
17480        } else {
17481            return mSettings.getInternalVersion();
17482        }
17483    }
17484
17485    private void deleteTempPackageFiles() {
17486        final FilenameFilter filter = new FilenameFilter() {
17487            public boolean accept(File dir, String name) {
17488                return name.startsWith("vmdl") && name.endsWith(".tmp");
17489            }
17490        };
17491        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17492            file.delete();
17493        }
17494    }
17495
17496    @Override
17497    public void deletePackageAsUser(String packageName, int versionCode,
17498            IPackageDeleteObserver observer, int userId, int flags) {
17499        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17500                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17501    }
17502
17503    @Override
17504    public void deletePackageVersioned(VersionedPackage versionedPackage,
17505            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17506        final int callingUid = Binder.getCallingUid();
17507        mContext.enforceCallingOrSelfPermission(
17508                android.Manifest.permission.DELETE_PACKAGES, null);
17509        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17510        Preconditions.checkNotNull(versionedPackage);
17511        Preconditions.checkNotNull(observer);
17512        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17513                PackageManager.VERSION_CODE_HIGHEST,
17514                Long.MAX_VALUE, "versionCode must be >= -1");
17515
17516        final String packageName = versionedPackage.getPackageName();
17517        final long versionCode = versionedPackage.getLongVersionCode();
17518        final String internalPackageName;
17519        synchronized (mPackages) {
17520            // Normalize package name to handle renamed packages and static libs
17521            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17522        }
17523
17524        final int uid = Binder.getCallingUid();
17525        if (!isOrphaned(internalPackageName)
17526                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17527            try {
17528                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17529                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17530                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17531                observer.onUserActionRequired(intent);
17532            } catch (RemoteException re) {
17533            }
17534            return;
17535        }
17536        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17537        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17538        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17539            mContext.enforceCallingOrSelfPermission(
17540                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17541                    "deletePackage for user " + userId);
17542        }
17543
17544        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17545            try {
17546                observer.onPackageDeleted(packageName,
17547                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17548            } catch (RemoteException re) {
17549            }
17550            return;
17551        }
17552
17553        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17554            try {
17555                observer.onPackageDeleted(packageName,
17556                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17557            } catch (RemoteException re) {
17558            }
17559            return;
17560        }
17561
17562        if (DEBUG_REMOVE) {
17563            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17564                    + " deleteAllUsers: " + deleteAllUsers + " version="
17565                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17566                    ? "VERSION_CODE_HIGHEST" : versionCode));
17567        }
17568        // Queue up an async operation since the package deletion may take a little while.
17569        mHandler.post(new Runnable() {
17570            public void run() {
17571                mHandler.removeCallbacks(this);
17572                int returnCode;
17573                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17574                boolean doDeletePackage = true;
17575                if (ps != null) {
17576                    final boolean targetIsInstantApp =
17577                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17578                    doDeletePackage = !targetIsInstantApp
17579                            || canViewInstantApps;
17580                }
17581                if (doDeletePackage) {
17582                    if (!deleteAllUsers) {
17583                        returnCode = deletePackageX(internalPackageName, versionCode,
17584                                userId, deleteFlags);
17585                    } else {
17586                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17587                                internalPackageName, users);
17588                        // If nobody is blocking uninstall, proceed with delete for all users
17589                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17590                            returnCode = deletePackageX(internalPackageName, versionCode,
17591                                    userId, deleteFlags);
17592                        } else {
17593                            // Otherwise uninstall individually for users with blockUninstalls=false
17594                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17595                            for (int userId : users) {
17596                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17597                                    returnCode = deletePackageX(internalPackageName, versionCode,
17598                                            userId, userFlags);
17599                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17600                                        Slog.w(TAG, "Package delete failed for user " + userId
17601                                                + ", returnCode " + returnCode);
17602                                    }
17603                                }
17604                            }
17605                            // The app has only been marked uninstalled for certain users.
17606                            // We still need to report that delete was blocked
17607                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17608                        }
17609                    }
17610                } else {
17611                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17612                }
17613                try {
17614                    observer.onPackageDeleted(packageName, returnCode, null);
17615                } catch (RemoteException e) {
17616                    Log.i(TAG, "Observer no longer exists.");
17617                } //end catch
17618            } //end run
17619        });
17620    }
17621
17622    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17623        if (pkg.staticSharedLibName != null) {
17624            return pkg.manifestPackageName;
17625        }
17626        return pkg.packageName;
17627    }
17628
17629    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17630        // Handle renamed packages
17631        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17632        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17633
17634        // Is this a static library?
17635        LongSparseArray<SharedLibraryEntry> versionedLib =
17636                mStaticLibsByDeclaringPackage.get(packageName);
17637        if (versionedLib == null || versionedLib.size() <= 0) {
17638            return packageName;
17639        }
17640
17641        // Figure out which lib versions the caller can see
17642        LongSparseLongArray versionsCallerCanSee = null;
17643        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17644        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17645                && callingAppId != Process.ROOT_UID) {
17646            versionsCallerCanSee = new LongSparseLongArray();
17647            String libName = versionedLib.valueAt(0).info.getName();
17648            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17649            if (uidPackages != null) {
17650                for (String uidPackage : uidPackages) {
17651                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17652                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17653                    if (libIdx >= 0) {
17654                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17655                        versionsCallerCanSee.append(libVersion, libVersion);
17656                    }
17657                }
17658            }
17659        }
17660
17661        // Caller can see nothing - done
17662        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17663            return packageName;
17664        }
17665
17666        // Find the version the caller can see and the app version code
17667        SharedLibraryEntry highestVersion = null;
17668        final int versionCount = versionedLib.size();
17669        for (int i = 0; i < versionCount; i++) {
17670            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17671            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17672                    libEntry.info.getLongVersion()) < 0) {
17673                continue;
17674            }
17675            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17676            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17677                if (libVersionCode == versionCode) {
17678                    return libEntry.apk;
17679                }
17680            } else if (highestVersion == null) {
17681                highestVersion = libEntry;
17682            } else if (libVersionCode  > highestVersion.info
17683                    .getDeclaringPackage().getLongVersionCode()) {
17684                highestVersion = libEntry;
17685            }
17686        }
17687
17688        if (highestVersion != null) {
17689            return highestVersion.apk;
17690        }
17691
17692        return packageName;
17693    }
17694
17695    boolean isCallerVerifier(int callingUid) {
17696        final int callingUserId = UserHandle.getUserId(callingUid);
17697        return mRequiredVerifierPackage != null &&
17698                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17699    }
17700
17701    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17702        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17703              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17704            return true;
17705        }
17706        final int callingUserId = UserHandle.getUserId(callingUid);
17707        // If the caller installed the pkgName, then allow it to silently uninstall.
17708        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17709            return true;
17710        }
17711
17712        // Allow package verifier to silently uninstall.
17713        if (mRequiredVerifierPackage != null &&
17714                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17715            return true;
17716        }
17717
17718        // Allow package uninstaller to silently uninstall.
17719        if (mRequiredUninstallerPackage != null &&
17720                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17721            return true;
17722        }
17723
17724        // Allow storage manager to silently uninstall.
17725        if (mStorageManagerPackage != null &&
17726                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17727            return true;
17728        }
17729
17730        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17731        // uninstall for device owner provisioning.
17732        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17733                == PERMISSION_GRANTED) {
17734            return true;
17735        }
17736
17737        return false;
17738    }
17739
17740    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17741        int[] result = EMPTY_INT_ARRAY;
17742        for (int userId : userIds) {
17743            if (getBlockUninstallForUser(packageName, userId)) {
17744                result = ArrayUtils.appendInt(result, userId);
17745            }
17746        }
17747        return result;
17748    }
17749
17750    @Override
17751    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17752        final int callingUid = Binder.getCallingUid();
17753        if (getInstantAppPackageName(callingUid) != null
17754                && !isCallerSameApp(packageName, callingUid)) {
17755            return false;
17756        }
17757        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17758    }
17759
17760    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17761        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17762                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17763        try {
17764            if (dpm != null) {
17765                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17766                        /* callingUserOnly =*/ false);
17767                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17768                        : deviceOwnerComponentName.getPackageName();
17769                // Does the package contains the device owner?
17770                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17771                // this check is probably not needed, since DO should be registered as a device
17772                // admin on some user too. (Original bug for this: b/17657954)
17773                if (packageName.equals(deviceOwnerPackageName)) {
17774                    return true;
17775                }
17776                // Does it contain a device admin for any user?
17777                int[] users;
17778                if (userId == UserHandle.USER_ALL) {
17779                    users = sUserManager.getUserIds();
17780                } else {
17781                    users = new int[]{userId};
17782                }
17783                for (int i = 0; i < users.length; ++i) {
17784                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17785                        return true;
17786                    }
17787                }
17788            }
17789        } catch (RemoteException e) {
17790        }
17791        return false;
17792    }
17793
17794    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17795        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17796    }
17797
17798    /**
17799     *  This method is an internal method that could be get invoked either
17800     *  to delete an installed package or to clean up a failed installation.
17801     *  After deleting an installed package, a broadcast is sent to notify any
17802     *  listeners that the package has been removed. For cleaning up a failed
17803     *  installation, the broadcast is not necessary since the package's
17804     *  installation wouldn't have sent the initial broadcast either
17805     *  The key steps in deleting a package are
17806     *  deleting the package information in internal structures like mPackages,
17807     *  deleting the packages base directories through installd
17808     *  updating mSettings to reflect current status
17809     *  persisting settings for later use
17810     *  sending a broadcast if necessary
17811     */
17812    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17813        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17814        final boolean res;
17815
17816        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17817                ? UserHandle.USER_ALL : userId;
17818
17819        if (isPackageDeviceAdmin(packageName, removeUser)) {
17820            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17821            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17822        }
17823
17824        PackageSetting uninstalledPs = null;
17825        PackageParser.Package pkg = null;
17826
17827        // for the uninstall-updates case and restricted profiles, remember the per-
17828        // user handle installed state
17829        int[] allUsers;
17830        synchronized (mPackages) {
17831            uninstalledPs = mSettings.mPackages.get(packageName);
17832            if (uninstalledPs == null) {
17833                Slog.w(TAG, "Not removing non-existent package " + packageName);
17834                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17835            }
17836
17837            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17838                    && uninstalledPs.versionCode != versionCode) {
17839                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17840                        + uninstalledPs.versionCode + " != " + versionCode);
17841                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17842            }
17843
17844            // Static shared libs can be declared by any package, so let us not
17845            // allow removing a package if it provides a lib others depend on.
17846            pkg = mPackages.get(packageName);
17847
17848            allUsers = sUserManager.getUserIds();
17849
17850            if (pkg != null && pkg.staticSharedLibName != null) {
17851                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17852                        pkg.staticSharedLibVersion);
17853                if (libEntry != null) {
17854                    for (int currUserId : allUsers) {
17855                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17856                            continue;
17857                        }
17858                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17859                                libEntry.info, 0, currUserId);
17860                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17861                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17862                                    + " hosting lib " + libEntry.info.getName() + " version "
17863                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17864                                    + " for user " + currUserId);
17865                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17866                        }
17867                    }
17868                }
17869            }
17870
17871            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17872        }
17873
17874        final int freezeUser;
17875        if (isUpdatedSystemApp(uninstalledPs)
17876                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17877            // We're downgrading a system app, which will apply to all users, so
17878            // freeze them all during the downgrade
17879            freezeUser = UserHandle.USER_ALL;
17880        } else {
17881            freezeUser = removeUser;
17882        }
17883
17884        synchronized (mInstallLock) {
17885            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17886            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17887                    deleteFlags, "deletePackageX")) {
17888                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17889                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17890            }
17891            synchronized (mPackages) {
17892                if (res) {
17893                    if (pkg != null) {
17894                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17895                    }
17896                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17897                    updateInstantAppInstallerLocked(packageName);
17898                }
17899            }
17900        }
17901
17902        if (res) {
17903            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17904            info.sendPackageRemovedBroadcasts(killApp);
17905            info.sendSystemPackageUpdatedBroadcasts();
17906            info.sendSystemPackageAppearedBroadcasts();
17907        }
17908        // Force a gc here.
17909        Runtime.getRuntime().gc();
17910        // Delete the resources here after sending the broadcast to let
17911        // other processes clean up before deleting resources.
17912        if (info.args != null) {
17913            synchronized (mInstallLock) {
17914                info.args.doPostDeleteLI(true);
17915            }
17916        }
17917
17918        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17919    }
17920
17921    static class PackageRemovedInfo {
17922        final PackageSender packageSender;
17923        String removedPackage;
17924        String installerPackageName;
17925        int uid = -1;
17926        int removedAppId = -1;
17927        int[] origUsers;
17928        int[] removedUsers = null;
17929        int[] broadcastUsers = null;
17930        int[] instantUserIds = null;
17931        SparseArray<Integer> installReasons;
17932        boolean isRemovedPackageSystemUpdate = false;
17933        boolean isUpdate;
17934        boolean dataRemoved;
17935        boolean removedForAllUsers;
17936        boolean isStaticSharedLib;
17937        // Clean up resources deleted packages.
17938        InstallArgs args = null;
17939        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17940        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17941
17942        PackageRemovedInfo(PackageSender packageSender) {
17943            this.packageSender = packageSender;
17944        }
17945
17946        void sendPackageRemovedBroadcasts(boolean killApp) {
17947            sendPackageRemovedBroadcastInternal(killApp);
17948            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17949            for (int i = 0; i < childCount; i++) {
17950                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17951                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17952            }
17953        }
17954
17955        void sendSystemPackageUpdatedBroadcasts() {
17956            if (isRemovedPackageSystemUpdate) {
17957                sendSystemPackageUpdatedBroadcastsInternal();
17958                final int childCount = (removedChildPackages != null)
17959                        ? removedChildPackages.size() : 0;
17960                for (int i = 0; i < childCount; i++) {
17961                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17962                    if (childInfo.isRemovedPackageSystemUpdate) {
17963                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17964                    }
17965                }
17966            }
17967        }
17968
17969        void sendSystemPackageAppearedBroadcasts() {
17970            final int packageCount = (appearedChildPackages != null)
17971                    ? appearedChildPackages.size() : 0;
17972            for (int i = 0; i < packageCount; i++) {
17973                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17974                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17975                    true /*sendBootCompleted*/, false /*startReceiver*/,
17976                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
17977            }
17978        }
17979
17980        private void sendSystemPackageUpdatedBroadcastsInternal() {
17981            Bundle extras = new Bundle(2);
17982            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17983            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17984            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17985                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17986            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17987                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17988            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17989                null, null, 0, removedPackage, null, null, null);
17990            if (installerPackageName != null) {
17991                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17992                        removedPackage, extras, 0 /*flags*/,
17993                        installerPackageName, null, null, null);
17994                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17995                        removedPackage, extras, 0 /*flags*/,
17996                        installerPackageName, null, null, null);
17997            }
17998        }
17999
18000        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18001            // Don't send static shared library removal broadcasts as these
18002            // libs are visible only the the apps that depend on them an one
18003            // cannot remove the library if it has a dependency.
18004            if (isStaticSharedLib) {
18005                return;
18006            }
18007            Bundle extras = new Bundle(2);
18008            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18009            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18010            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18011            if (isUpdate || isRemovedPackageSystemUpdate) {
18012                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18013            }
18014            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18015            if (removedPackage != null) {
18016                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18017                    removedPackage, extras, 0, null /*targetPackage*/, null,
18018                    broadcastUsers, instantUserIds);
18019                if (installerPackageName != null) {
18020                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18021                            removedPackage, extras, 0 /*flags*/,
18022                            installerPackageName, null, broadcastUsers, instantUserIds);
18023                }
18024                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18025                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18026                        removedPackage, extras,
18027                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18028                        null, null, broadcastUsers, instantUserIds);
18029                    packageSender.notifyPackageRemoved(removedPackage);
18030                }
18031            }
18032            if (removedAppId >= 0) {
18033                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18034                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18035                    null, null, broadcastUsers, instantUserIds);
18036            }
18037        }
18038
18039        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18040            removedUsers = userIds;
18041            if (removedUsers == null) {
18042                broadcastUsers = null;
18043                return;
18044            }
18045
18046            broadcastUsers = EMPTY_INT_ARRAY;
18047            instantUserIds = EMPTY_INT_ARRAY;
18048            for (int i = userIds.length - 1; i >= 0; --i) {
18049                final int userId = userIds[i];
18050                if (deletedPackageSetting.getInstantApp(userId)) {
18051                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18052                } else {
18053                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18054                }
18055            }
18056        }
18057    }
18058
18059    /*
18060     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18061     * flag is not set, the data directory is removed as well.
18062     * make sure this flag is set for partially installed apps. If not its meaningless to
18063     * delete a partially installed application.
18064     */
18065    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18066            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18067        String packageName = ps.name;
18068        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18069        // Retrieve object to delete permissions for shared user later on
18070        final PackageParser.Package deletedPkg;
18071        final PackageSetting deletedPs;
18072        // reader
18073        synchronized (mPackages) {
18074            deletedPkg = mPackages.get(packageName);
18075            deletedPs = mSettings.mPackages.get(packageName);
18076            if (outInfo != null) {
18077                outInfo.removedPackage = packageName;
18078                outInfo.installerPackageName = ps.installerPackageName;
18079                outInfo.isStaticSharedLib = deletedPkg != null
18080                        && deletedPkg.staticSharedLibName != null;
18081                outInfo.populateUsers(deletedPs == null ? null
18082                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18083            }
18084        }
18085
18086        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18087
18088        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18089            final PackageParser.Package resolvedPkg;
18090            if (deletedPkg != null) {
18091                resolvedPkg = deletedPkg;
18092            } else {
18093                // We don't have a parsed package when it lives on an ejected
18094                // adopted storage device, so fake something together
18095                resolvedPkg = new PackageParser.Package(ps.name);
18096                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18097            }
18098            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18099                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18100            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18101            if (outInfo != null) {
18102                outInfo.dataRemoved = true;
18103            }
18104            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18105        }
18106
18107        int removedAppId = -1;
18108
18109        // writer
18110        synchronized (mPackages) {
18111            boolean installedStateChanged = false;
18112            if (deletedPs != null) {
18113                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18114                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18115                    clearDefaultBrowserIfNeeded(packageName);
18116                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18117                    removedAppId = mSettings.removePackageLPw(packageName);
18118                    if (outInfo != null) {
18119                        outInfo.removedAppId = removedAppId;
18120                    }
18121                    mPermissionManager.updatePermissions(
18122                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18123                    if (deletedPs.sharedUser != null) {
18124                        // Remove permissions associated with package. Since runtime
18125                        // permissions are per user we have to kill the removed package
18126                        // or packages running under the shared user of the removed
18127                        // package if revoking the permissions requested only by the removed
18128                        // package is successful and this causes a change in gids.
18129                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18130                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18131                                    userId);
18132                            if (userIdToKill == UserHandle.USER_ALL
18133                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18134                                // If gids changed for this user, kill all affected packages.
18135                                mHandler.post(new Runnable() {
18136                                    @Override
18137                                    public void run() {
18138                                        // This has to happen with no lock held.
18139                                        killApplication(deletedPs.name, deletedPs.appId,
18140                                                KILL_APP_REASON_GIDS_CHANGED);
18141                                    }
18142                                });
18143                                break;
18144                            }
18145                        }
18146                    }
18147                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18148                }
18149                // make sure to preserve per-user disabled state if this removal was just
18150                // a downgrade of a system app to the factory package
18151                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18152                    if (DEBUG_REMOVE) {
18153                        Slog.d(TAG, "Propagating install state across downgrade");
18154                    }
18155                    for (int userId : allUserHandles) {
18156                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18157                        if (DEBUG_REMOVE) {
18158                            Slog.d(TAG, "    user " + userId + " => " + installed);
18159                        }
18160                        if (installed != ps.getInstalled(userId)) {
18161                            installedStateChanged = true;
18162                        }
18163                        ps.setInstalled(installed, userId);
18164                    }
18165                }
18166            }
18167            // can downgrade to reader
18168            if (writeSettings) {
18169                // Save settings now
18170                mSettings.writeLPr();
18171            }
18172            if (installedStateChanged) {
18173                mSettings.writeKernelMappingLPr(ps);
18174            }
18175        }
18176        if (removedAppId != -1) {
18177            // A user ID was deleted here. Go through all users and remove it
18178            // from KeyStore.
18179            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18180        }
18181    }
18182
18183    static boolean locationIsPrivileged(String path) {
18184        try {
18185            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18186            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18187            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18188            return path.startsWith(privilegedAppDir.getCanonicalPath())
18189                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18190                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18191        } catch (IOException e) {
18192            Slog.e(TAG, "Unable to access code path " + path);
18193        }
18194        return false;
18195    }
18196
18197    static boolean locationIsOem(String path) {
18198        try {
18199            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18200        } catch (IOException e) {
18201            Slog.e(TAG, "Unable to access code path " + path);
18202        }
18203        return false;
18204    }
18205
18206    static boolean locationIsVendor(String path) {
18207        try {
18208            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
18209        } catch (IOException e) {
18210            Slog.e(TAG, "Unable to access code path " + path);
18211        }
18212        return false;
18213    }
18214
18215    static boolean locationIsProduct(String path) {
18216        try {
18217            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18218        } catch (IOException e) {
18219            Slog.e(TAG, "Unable to access code path " + path);
18220        }
18221        return false;
18222    }
18223
18224    /*
18225     * Tries to delete system package.
18226     */
18227    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18228            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18229            boolean writeSettings) {
18230        if (deletedPs.parentPackageName != null) {
18231            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18232            return false;
18233        }
18234
18235        final boolean applyUserRestrictions
18236                = (allUserHandles != null) && (outInfo.origUsers != null);
18237        final PackageSetting disabledPs;
18238        // Confirm if the system package has been updated
18239        // An updated system app can be deleted. This will also have to restore
18240        // the system pkg from system partition
18241        // reader
18242        synchronized (mPackages) {
18243            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18244        }
18245
18246        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18247                + " disabledPs=" + disabledPs);
18248
18249        if (disabledPs == null) {
18250            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18251            return false;
18252        } else if (DEBUG_REMOVE) {
18253            Slog.d(TAG, "Deleting system pkg from data partition");
18254        }
18255
18256        if (DEBUG_REMOVE) {
18257            if (applyUserRestrictions) {
18258                Slog.d(TAG, "Remembering install states:");
18259                for (int userId : allUserHandles) {
18260                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18261                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18262                }
18263            }
18264        }
18265
18266        // Delete the updated package
18267        outInfo.isRemovedPackageSystemUpdate = true;
18268        if (outInfo.removedChildPackages != null) {
18269            final int childCount = (deletedPs.childPackageNames != null)
18270                    ? deletedPs.childPackageNames.size() : 0;
18271            for (int i = 0; i < childCount; i++) {
18272                String childPackageName = deletedPs.childPackageNames.get(i);
18273                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18274                        .contains(childPackageName)) {
18275                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18276                            childPackageName);
18277                    if (childInfo != null) {
18278                        childInfo.isRemovedPackageSystemUpdate = true;
18279                    }
18280                }
18281            }
18282        }
18283
18284        if (disabledPs.versionCode < deletedPs.versionCode) {
18285            // Delete data for downgrades
18286            flags &= ~PackageManager.DELETE_KEEP_DATA;
18287        } else {
18288            // Preserve data by setting flag
18289            flags |= PackageManager.DELETE_KEEP_DATA;
18290        }
18291
18292        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18293                outInfo, writeSettings, disabledPs.pkg);
18294        if (!ret) {
18295            return false;
18296        }
18297
18298        // writer
18299        synchronized (mPackages) {
18300            // NOTE: The system package always needs to be enabled; even if it's for
18301            // a compressed stub. If we don't, installing the system package fails
18302            // during scan [scanning checks the disabled packages]. We will reverse
18303            // this later, after we've "installed" the stub.
18304            // Reinstate the old system package
18305            enableSystemPackageLPw(disabledPs.pkg);
18306            // Remove any native libraries from the upgraded package.
18307            removeNativeBinariesLI(deletedPs);
18308        }
18309
18310        // Install the system package
18311        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18312        try {
18313            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18314                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18315        } catch (PackageManagerException e) {
18316            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18317                    + e.getMessage());
18318            return false;
18319        } finally {
18320            if (disabledPs.pkg.isStub) {
18321                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18322            }
18323        }
18324        return true;
18325    }
18326
18327    /**
18328     * Installs a package that's already on the system partition.
18329     */
18330    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18331            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18332            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18333                    throws PackageManagerException {
18334        @ParseFlags int parseFlags =
18335                mDefParseFlags
18336                | PackageParser.PARSE_MUST_BE_APK
18337                | PackageParser.PARSE_IS_SYSTEM_DIR;
18338        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18339        if (isPrivileged || locationIsPrivileged(codePathString)) {
18340            scanFlags |= SCAN_AS_PRIVILEGED;
18341        }
18342        if (locationIsOem(codePathString)) {
18343            scanFlags |= SCAN_AS_OEM;
18344        }
18345        if (locationIsVendor(codePathString)) {
18346            scanFlags |= SCAN_AS_VENDOR;
18347        }
18348        if (locationIsProduct(codePathString)) {
18349            scanFlags |= SCAN_AS_PRODUCT;
18350        }
18351
18352        final File codePath = new File(codePathString);
18353        final PackageParser.Package pkg =
18354                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18355
18356        try {
18357            // update shared libraries for the newly re-installed system package
18358            updateSharedLibrariesLPr(pkg, null);
18359        } catch (PackageManagerException e) {
18360            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18361        }
18362
18363        prepareAppDataAfterInstallLIF(pkg);
18364
18365        // writer
18366        synchronized (mPackages) {
18367            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18368
18369            // Propagate the permissions state as we do not want to drop on the floor
18370            // runtime permissions. The update permissions method below will take
18371            // care of removing obsolete permissions and grant install permissions.
18372            if (origPermissionState != null) {
18373                ps.getPermissionsState().copyFrom(origPermissionState);
18374            }
18375            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18376                    mPermissionCallback);
18377
18378            final boolean applyUserRestrictions
18379                    = (allUserHandles != null) && (origUserHandles != null);
18380            if (applyUserRestrictions) {
18381                boolean installedStateChanged = false;
18382                if (DEBUG_REMOVE) {
18383                    Slog.d(TAG, "Propagating install state across reinstall");
18384                }
18385                for (int userId : allUserHandles) {
18386                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18387                    if (DEBUG_REMOVE) {
18388                        Slog.d(TAG, "    user " + userId + " => " + installed);
18389                    }
18390                    if (installed != ps.getInstalled(userId)) {
18391                        installedStateChanged = true;
18392                    }
18393                    ps.setInstalled(installed, userId);
18394
18395                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18396                }
18397                // Regardless of writeSettings we need to ensure that this restriction
18398                // state propagation is persisted
18399                mSettings.writeAllUsersPackageRestrictionsLPr();
18400                if (installedStateChanged) {
18401                    mSettings.writeKernelMappingLPr(ps);
18402                }
18403            }
18404            // can downgrade to reader here
18405            if (writeSettings) {
18406                mSettings.writeLPr();
18407            }
18408        }
18409        return pkg;
18410    }
18411
18412    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18413            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18414            PackageRemovedInfo outInfo, boolean writeSettings,
18415            PackageParser.Package replacingPackage) {
18416        synchronized (mPackages) {
18417            if (outInfo != null) {
18418                outInfo.uid = ps.appId;
18419            }
18420
18421            if (outInfo != null && outInfo.removedChildPackages != null) {
18422                final int childCount = (ps.childPackageNames != null)
18423                        ? ps.childPackageNames.size() : 0;
18424                for (int i = 0; i < childCount; i++) {
18425                    String childPackageName = ps.childPackageNames.get(i);
18426                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18427                    if (childPs == null) {
18428                        return false;
18429                    }
18430                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18431                            childPackageName);
18432                    if (childInfo != null) {
18433                        childInfo.uid = childPs.appId;
18434                    }
18435                }
18436            }
18437        }
18438
18439        // Delete package data from internal structures and also remove data if flag is set
18440        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18441
18442        // Delete the child packages data
18443        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18444        for (int i = 0; i < childCount; i++) {
18445            PackageSetting childPs;
18446            synchronized (mPackages) {
18447                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18448            }
18449            if (childPs != null) {
18450                PackageRemovedInfo childOutInfo = (outInfo != null
18451                        && outInfo.removedChildPackages != null)
18452                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18453                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18454                        && (replacingPackage != null
18455                        && !replacingPackage.hasChildPackage(childPs.name))
18456                        ? flags & ~DELETE_KEEP_DATA : flags;
18457                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18458                        deleteFlags, writeSettings);
18459            }
18460        }
18461
18462        // Delete application code and resources only for parent packages
18463        if (ps.parentPackageName == null) {
18464            if (deleteCodeAndResources && (outInfo != null)) {
18465                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18466                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18467                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18468            }
18469        }
18470
18471        return true;
18472    }
18473
18474    @Override
18475    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18476            int userId) {
18477        mContext.enforceCallingOrSelfPermission(
18478                android.Manifest.permission.DELETE_PACKAGES, null);
18479        synchronized (mPackages) {
18480            // Cannot block uninstall of static shared libs as they are
18481            // considered a part of the using app (emulating static linking).
18482            // Also static libs are installed always on internal storage.
18483            PackageParser.Package pkg = mPackages.get(packageName);
18484            if (pkg != null && pkg.staticSharedLibName != null) {
18485                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18486                        + " providing static shared library: " + pkg.staticSharedLibName);
18487                return false;
18488            }
18489            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18490            mSettings.writePackageRestrictionsLPr(userId);
18491        }
18492        return true;
18493    }
18494
18495    @Override
18496    public boolean getBlockUninstallForUser(String packageName, int userId) {
18497        synchronized (mPackages) {
18498            final PackageSetting ps = mSettings.mPackages.get(packageName);
18499            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18500                return false;
18501            }
18502            return mSettings.getBlockUninstallLPr(userId, packageName);
18503        }
18504    }
18505
18506    @Override
18507    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18508        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18509        synchronized (mPackages) {
18510            PackageSetting ps = mSettings.mPackages.get(packageName);
18511            if (ps == null) {
18512                Log.w(TAG, "Package doesn't exist: " + packageName);
18513                return false;
18514            }
18515            if (systemUserApp) {
18516                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18517            } else {
18518                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18519            }
18520            mSettings.writeLPr();
18521        }
18522        return true;
18523    }
18524
18525    /*
18526     * This method handles package deletion in general
18527     */
18528    private boolean deletePackageLIF(String packageName, UserHandle user,
18529            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18530            PackageRemovedInfo outInfo, boolean writeSettings,
18531            PackageParser.Package replacingPackage) {
18532        if (packageName == null) {
18533            Slog.w(TAG, "Attempt to delete null packageName.");
18534            return false;
18535        }
18536
18537        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18538
18539        PackageSetting ps;
18540        synchronized (mPackages) {
18541            ps = mSettings.mPackages.get(packageName);
18542            if (ps == null) {
18543                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18544                return false;
18545            }
18546
18547            if (ps.parentPackageName != null && (!isSystemApp(ps)
18548                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18549                if (DEBUG_REMOVE) {
18550                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18551                            + ((user == null) ? UserHandle.USER_ALL : user));
18552                }
18553                final int removedUserId = (user != null) ? user.getIdentifier()
18554                        : UserHandle.USER_ALL;
18555                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18556                    return false;
18557                }
18558                markPackageUninstalledForUserLPw(ps, user);
18559                scheduleWritePackageRestrictionsLocked(user);
18560                return true;
18561            }
18562        }
18563
18564        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18565                && user.getIdentifier() != UserHandle.USER_ALL)) {
18566            // The caller is asking that the package only be deleted for a single
18567            // user.  To do this, we just mark its uninstalled state and delete
18568            // its data. If this is a system app, we only allow this to happen if
18569            // they have set the special DELETE_SYSTEM_APP which requests different
18570            // semantics than normal for uninstalling system apps.
18571            markPackageUninstalledForUserLPw(ps, user);
18572
18573            if (!isSystemApp(ps)) {
18574                // Do not uninstall the APK if an app should be cached
18575                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18576                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18577                    // Other user still have this package installed, so all
18578                    // we need to do is clear this user's data and save that
18579                    // it is uninstalled.
18580                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18581                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18582                        return false;
18583                    }
18584                    scheduleWritePackageRestrictionsLocked(user);
18585                    return true;
18586                } else {
18587                    // We need to set it back to 'installed' so the uninstall
18588                    // broadcasts will be sent correctly.
18589                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18590                    ps.setInstalled(true, user.getIdentifier());
18591                    mSettings.writeKernelMappingLPr(ps);
18592                }
18593            } else {
18594                // This is a system app, so we assume that the
18595                // other users still have this package installed, so all
18596                // we need to do is clear this user's data and save that
18597                // it is uninstalled.
18598                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18599                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18600                    return false;
18601                }
18602                scheduleWritePackageRestrictionsLocked(user);
18603                return true;
18604            }
18605        }
18606
18607        // If we are deleting a composite package for all users, keep track
18608        // of result for each child.
18609        if (ps.childPackageNames != null && outInfo != null) {
18610            synchronized (mPackages) {
18611                final int childCount = ps.childPackageNames.size();
18612                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18613                for (int i = 0; i < childCount; i++) {
18614                    String childPackageName = ps.childPackageNames.get(i);
18615                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18616                    childInfo.removedPackage = childPackageName;
18617                    childInfo.installerPackageName = ps.installerPackageName;
18618                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18619                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18620                    if (childPs != null) {
18621                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18622                    }
18623                }
18624            }
18625        }
18626
18627        boolean ret = false;
18628        if (isSystemApp(ps)) {
18629            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18630            // When an updated system application is deleted we delete the existing resources
18631            // as well and fall back to existing code in system partition
18632            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18633        } else {
18634            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18635            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18636                    outInfo, writeSettings, replacingPackage);
18637        }
18638
18639        // Take a note whether we deleted the package for all users
18640        if (outInfo != null) {
18641            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18642            if (outInfo.removedChildPackages != null) {
18643                synchronized (mPackages) {
18644                    final int childCount = outInfo.removedChildPackages.size();
18645                    for (int i = 0; i < childCount; i++) {
18646                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18647                        if (childInfo != null) {
18648                            childInfo.removedForAllUsers = mPackages.get(
18649                                    childInfo.removedPackage) == null;
18650                        }
18651                    }
18652                }
18653            }
18654            // If we uninstalled an update to a system app there may be some
18655            // child packages that appeared as they are declared in the system
18656            // app but were not declared in the update.
18657            if (isSystemApp(ps)) {
18658                synchronized (mPackages) {
18659                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18660                    final int childCount = (updatedPs.childPackageNames != null)
18661                            ? updatedPs.childPackageNames.size() : 0;
18662                    for (int i = 0; i < childCount; i++) {
18663                        String childPackageName = updatedPs.childPackageNames.get(i);
18664                        if (outInfo.removedChildPackages == null
18665                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18666                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18667                            if (childPs == null) {
18668                                continue;
18669                            }
18670                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18671                            installRes.name = childPackageName;
18672                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18673                            installRes.pkg = mPackages.get(childPackageName);
18674                            installRes.uid = childPs.pkg.applicationInfo.uid;
18675                            if (outInfo.appearedChildPackages == null) {
18676                                outInfo.appearedChildPackages = new ArrayMap<>();
18677                            }
18678                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18679                        }
18680                    }
18681                }
18682            }
18683        }
18684
18685        return ret;
18686    }
18687
18688    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18689        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18690                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18691        for (int nextUserId : userIds) {
18692            if (DEBUG_REMOVE) {
18693                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18694            }
18695            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18696                    false /*installed*/,
18697                    true /*stopped*/,
18698                    true /*notLaunched*/,
18699                    false /*hidden*/,
18700                    false /*suspended*/,
18701                    false /*instantApp*/,
18702                    false /*virtualPreload*/,
18703                    null /*lastDisableAppCaller*/,
18704                    null /*enabledComponents*/,
18705                    null /*disabledComponents*/,
18706                    ps.readUserState(nextUserId).domainVerificationStatus,
18707                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18708                    null /*harmfulAppWarning*/);
18709        }
18710        mSettings.writeKernelMappingLPr(ps);
18711    }
18712
18713    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18714            PackageRemovedInfo outInfo) {
18715        final PackageParser.Package pkg;
18716        synchronized (mPackages) {
18717            pkg = mPackages.get(ps.name);
18718        }
18719
18720        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18721                : new int[] {userId};
18722        for (int nextUserId : userIds) {
18723            if (DEBUG_REMOVE) {
18724                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18725                        + nextUserId);
18726            }
18727
18728            destroyAppDataLIF(pkg, userId,
18729                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18730            destroyAppProfilesLIF(pkg, userId);
18731            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18732            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18733            schedulePackageCleaning(ps.name, nextUserId, false);
18734            synchronized (mPackages) {
18735                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18736                    scheduleWritePackageRestrictionsLocked(nextUserId);
18737                }
18738                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18739            }
18740        }
18741
18742        if (outInfo != null) {
18743            outInfo.removedPackage = ps.name;
18744            outInfo.installerPackageName = ps.installerPackageName;
18745            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18746            outInfo.removedAppId = ps.appId;
18747            outInfo.removedUsers = userIds;
18748            outInfo.broadcastUsers = userIds;
18749        }
18750
18751        return true;
18752    }
18753
18754    private final class ClearStorageConnection implements ServiceConnection {
18755        IMediaContainerService mContainerService;
18756
18757        @Override
18758        public void onServiceConnected(ComponentName name, IBinder service) {
18759            synchronized (this) {
18760                mContainerService = IMediaContainerService.Stub
18761                        .asInterface(Binder.allowBlocking(service));
18762                notifyAll();
18763            }
18764        }
18765
18766        @Override
18767        public void onServiceDisconnected(ComponentName name) {
18768        }
18769    }
18770
18771    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18772        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18773
18774        final boolean mounted;
18775        if (Environment.isExternalStorageEmulated()) {
18776            mounted = true;
18777        } else {
18778            final String status = Environment.getExternalStorageState();
18779
18780            mounted = status.equals(Environment.MEDIA_MOUNTED)
18781                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18782        }
18783
18784        if (!mounted) {
18785            return;
18786        }
18787
18788        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18789        int[] users;
18790        if (userId == UserHandle.USER_ALL) {
18791            users = sUserManager.getUserIds();
18792        } else {
18793            users = new int[] { userId };
18794        }
18795        final ClearStorageConnection conn = new ClearStorageConnection();
18796        if (mContext.bindServiceAsUser(
18797                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18798            try {
18799                for (int curUser : users) {
18800                    long timeout = SystemClock.uptimeMillis() + 5000;
18801                    synchronized (conn) {
18802                        long now;
18803                        while (conn.mContainerService == null &&
18804                                (now = SystemClock.uptimeMillis()) < timeout) {
18805                            try {
18806                                conn.wait(timeout - now);
18807                            } catch (InterruptedException e) {
18808                            }
18809                        }
18810                    }
18811                    if (conn.mContainerService == null) {
18812                        return;
18813                    }
18814
18815                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18816                    clearDirectory(conn.mContainerService,
18817                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18818                    if (allData) {
18819                        clearDirectory(conn.mContainerService,
18820                                userEnv.buildExternalStorageAppDataDirs(packageName));
18821                        clearDirectory(conn.mContainerService,
18822                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18823                    }
18824                }
18825            } finally {
18826                mContext.unbindService(conn);
18827            }
18828        }
18829    }
18830
18831    @Override
18832    public void clearApplicationProfileData(String packageName) {
18833        enforceSystemOrRoot("Only the system can clear all profile data");
18834
18835        final PackageParser.Package pkg;
18836        synchronized (mPackages) {
18837            pkg = mPackages.get(packageName);
18838        }
18839
18840        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18841            synchronized (mInstallLock) {
18842                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18843            }
18844        }
18845    }
18846
18847    @Override
18848    public void clearApplicationUserData(final String packageName,
18849            final IPackageDataObserver observer, final int userId) {
18850        mContext.enforceCallingOrSelfPermission(
18851                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18852
18853        final int callingUid = Binder.getCallingUid();
18854        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18855                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18856
18857        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18858        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18859        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18860            throw new SecurityException("Cannot clear data for a protected package: "
18861                    + packageName);
18862        }
18863        // Queue up an async operation since the package deletion may take a little while.
18864        mHandler.post(new Runnable() {
18865            public void run() {
18866                mHandler.removeCallbacks(this);
18867                final boolean succeeded;
18868                if (!filterApp) {
18869                    try (PackageFreezer freezer = freezePackage(packageName,
18870                            "clearApplicationUserData")) {
18871                        synchronized (mInstallLock) {
18872                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18873                        }
18874                        clearExternalStorageDataSync(packageName, userId, true);
18875                        synchronized (mPackages) {
18876                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18877                                    packageName, userId);
18878                        }
18879                    }
18880                    if (succeeded) {
18881                        // invoke DeviceStorageMonitor's update method to clear any notifications
18882                        DeviceStorageMonitorInternal dsm = LocalServices
18883                                .getService(DeviceStorageMonitorInternal.class);
18884                        if (dsm != null) {
18885                            dsm.checkMemory();
18886                        }
18887                    }
18888                } else {
18889                    succeeded = false;
18890                }
18891                if (observer != null) {
18892                    try {
18893                        observer.onRemoveCompleted(packageName, succeeded);
18894                    } catch (RemoteException e) {
18895                        Log.i(TAG, "Observer no longer exists.");
18896                    }
18897                } //end if observer
18898            } //end run
18899        });
18900    }
18901
18902    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18903        if (packageName == null) {
18904            Slog.w(TAG, "Attempt to delete null packageName.");
18905            return false;
18906        }
18907
18908        // Try finding details about the requested package
18909        PackageParser.Package pkg;
18910        synchronized (mPackages) {
18911            pkg = mPackages.get(packageName);
18912            if (pkg == null) {
18913                final PackageSetting ps = mSettings.mPackages.get(packageName);
18914                if (ps != null) {
18915                    pkg = ps.pkg;
18916                }
18917            }
18918
18919            if (pkg == null) {
18920                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18921                return false;
18922            }
18923
18924            PackageSetting ps = (PackageSetting) pkg.mExtras;
18925            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18926        }
18927
18928        clearAppDataLIF(pkg, userId,
18929                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18930
18931        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18932        removeKeystoreDataIfNeeded(userId, appId);
18933
18934        UserManagerInternal umInternal = getUserManagerInternal();
18935        final int flags;
18936        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18937            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18938        } else if (umInternal.isUserRunning(userId)) {
18939            flags = StorageManager.FLAG_STORAGE_DE;
18940        } else {
18941            flags = 0;
18942        }
18943        prepareAppDataContentsLIF(pkg, userId, flags);
18944
18945        return true;
18946    }
18947
18948    /**
18949     * Reverts user permission state changes (permissions and flags) in
18950     * all packages for a given user.
18951     *
18952     * @param userId The device user for which to do a reset.
18953     */
18954    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18955        final int packageCount = mPackages.size();
18956        for (int i = 0; i < packageCount; i++) {
18957            PackageParser.Package pkg = mPackages.valueAt(i);
18958            PackageSetting ps = (PackageSetting) pkg.mExtras;
18959            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18960        }
18961    }
18962
18963    private void resetNetworkPolicies(int userId) {
18964        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18965    }
18966
18967    /**
18968     * Reverts user permission state changes (permissions and flags).
18969     *
18970     * @param ps The package for which to reset.
18971     * @param userId The device user for which to do a reset.
18972     */
18973    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18974            final PackageSetting ps, final int userId) {
18975        if (ps.pkg == null) {
18976            return;
18977        }
18978
18979        // These are flags that can change base on user actions.
18980        final int userSettableMask = FLAG_PERMISSION_USER_SET
18981                | FLAG_PERMISSION_USER_FIXED
18982                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18983                | FLAG_PERMISSION_REVIEW_REQUIRED;
18984
18985        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18986                | FLAG_PERMISSION_POLICY_FIXED;
18987
18988        boolean writeInstallPermissions = false;
18989        boolean writeRuntimePermissions = false;
18990
18991        final int permissionCount = ps.pkg.requestedPermissions.size();
18992        for (int i = 0; i < permissionCount; i++) {
18993            final String permName = ps.pkg.requestedPermissions.get(i);
18994            final BasePermission bp =
18995                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18996            if (bp == null) {
18997                continue;
18998            }
18999
19000            // If shared user we just reset the state to which only this app contributed.
19001            if (ps.sharedUser != null) {
19002                boolean used = false;
19003                final int packageCount = ps.sharedUser.packages.size();
19004                for (int j = 0; j < packageCount; j++) {
19005                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19006                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19007                            && pkg.pkg.requestedPermissions.contains(permName)) {
19008                        used = true;
19009                        break;
19010                    }
19011                }
19012                if (used) {
19013                    continue;
19014                }
19015            }
19016
19017            final PermissionsState permissionsState = ps.getPermissionsState();
19018
19019            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19020
19021            // Always clear the user settable flags.
19022            final boolean hasInstallState =
19023                    permissionsState.getInstallPermissionState(permName) != null;
19024            // If permission review is enabled and this is a legacy app, mark the
19025            // permission as requiring a review as this is the initial state.
19026            int flags = 0;
19027            if (mSettings.mPermissions.mPermissionReviewRequired
19028                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19029                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19030            }
19031            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19032                if (hasInstallState) {
19033                    writeInstallPermissions = true;
19034                } else {
19035                    writeRuntimePermissions = true;
19036                }
19037            }
19038
19039            // Below is only runtime permission handling.
19040            if (!bp.isRuntime()) {
19041                continue;
19042            }
19043
19044            // Never clobber system or policy.
19045            if ((oldFlags & policyOrSystemFlags) != 0) {
19046                continue;
19047            }
19048
19049            // If this permission was granted by default, make sure it is.
19050            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19051                if (permissionsState.grantRuntimePermission(bp, userId)
19052                        != PERMISSION_OPERATION_FAILURE) {
19053                    writeRuntimePermissions = true;
19054                }
19055            // If permission review is enabled the permissions for a legacy apps
19056            // are represented as constantly granted runtime ones, so don't revoke.
19057            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19058                // Otherwise, reset the permission.
19059                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19060                switch (revokeResult) {
19061                    case PERMISSION_OPERATION_SUCCESS:
19062                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19063                        writeRuntimePermissions = true;
19064                        final int appId = ps.appId;
19065                        mHandler.post(new Runnable() {
19066                            @Override
19067                            public void run() {
19068                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19069                            }
19070                        });
19071                    } break;
19072                }
19073            }
19074        }
19075
19076        // Synchronously write as we are taking permissions away.
19077        if (writeRuntimePermissions) {
19078            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19079        }
19080
19081        // Synchronously write as we are taking permissions away.
19082        if (writeInstallPermissions) {
19083            mSettings.writeLPr();
19084        }
19085    }
19086
19087    /**
19088     * Remove entries from the keystore daemon. Will only remove it if the
19089     * {@code appId} is valid.
19090     */
19091    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19092        if (appId < 0) {
19093            return;
19094        }
19095
19096        final KeyStore keyStore = KeyStore.getInstance();
19097        if (keyStore != null) {
19098            if (userId == UserHandle.USER_ALL) {
19099                for (final int individual : sUserManager.getUserIds()) {
19100                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19101                }
19102            } else {
19103                keyStore.clearUid(UserHandle.getUid(userId, appId));
19104            }
19105        } else {
19106            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19107        }
19108    }
19109
19110    @Override
19111    public void deleteApplicationCacheFiles(final String packageName,
19112            final IPackageDataObserver observer) {
19113        final int userId = UserHandle.getCallingUserId();
19114        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19115    }
19116
19117    @Override
19118    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19119            final IPackageDataObserver observer) {
19120        final int callingUid = Binder.getCallingUid();
19121        if (mContext.checkCallingOrSelfPermission(
19122                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19123                != PackageManager.PERMISSION_GRANTED) {
19124            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19125            if (mContext.checkCallingOrSelfPermission(
19126                    android.Manifest.permission.DELETE_CACHE_FILES)
19127                    == PackageManager.PERMISSION_GRANTED) {
19128                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19129                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19130                        ", silently ignoring");
19131                return;
19132            }
19133            mContext.enforceCallingOrSelfPermission(
19134                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19135        }
19136        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19137                /* requireFullPermission= */ true, /* checkShell= */ false,
19138                "delete application cache files");
19139        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19140                android.Manifest.permission.ACCESS_INSTANT_APPS);
19141
19142        final PackageParser.Package pkg;
19143        synchronized (mPackages) {
19144            pkg = mPackages.get(packageName);
19145        }
19146
19147        // Queue up an async operation since the package deletion may take a little while.
19148        mHandler.post(new Runnable() {
19149            public void run() {
19150                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19151                boolean doClearData = true;
19152                if (ps != null) {
19153                    final boolean targetIsInstantApp =
19154                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19155                    doClearData = !targetIsInstantApp
19156                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19157                }
19158                if (doClearData) {
19159                    synchronized (mInstallLock) {
19160                        final int flags = StorageManager.FLAG_STORAGE_DE
19161                                | StorageManager.FLAG_STORAGE_CE;
19162                        // We're only clearing cache files, so we don't care if the
19163                        // app is unfrozen and still able to run
19164                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19165                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19166                    }
19167                    clearExternalStorageDataSync(packageName, userId, false);
19168                }
19169                if (observer != null) {
19170                    try {
19171                        observer.onRemoveCompleted(packageName, true);
19172                    } catch (RemoteException e) {
19173                        Log.i(TAG, "Observer no longer exists.");
19174                    }
19175                }
19176            }
19177        });
19178    }
19179
19180    @Override
19181    public void getPackageSizeInfo(final String packageName, int userHandle,
19182            final IPackageStatsObserver observer) {
19183        throw new UnsupportedOperationException(
19184                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19185    }
19186
19187    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19188        final PackageSetting ps;
19189        synchronized (mPackages) {
19190            ps = mSettings.mPackages.get(packageName);
19191            if (ps == null) {
19192                Slog.w(TAG, "Failed to find settings for " + packageName);
19193                return false;
19194            }
19195        }
19196
19197        final String[] packageNames = { packageName };
19198        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19199        final String[] codePaths = { ps.codePathString };
19200
19201        try {
19202            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19203                    ps.appId, ceDataInodes, codePaths, stats);
19204
19205            // For now, ignore code size of packages on system partition
19206            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19207                stats.codeSize = 0;
19208            }
19209
19210            // External clients expect these to be tracked separately
19211            stats.dataSize -= stats.cacheSize;
19212
19213        } catch (InstallerException e) {
19214            Slog.w(TAG, String.valueOf(e));
19215            return false;
19216        }
19217
19218        return true;
19219    }
19220
19221    private int getUidTargetSdkVersionLockedLPr(int uid) {
19222        Object obj = mSettings.getUserIdLPr(uid);
19223        if (obj instanceof SharedUserSetting) {
19224            final SharedUserSetting sus = (SharedUserSetting) obj;
19225            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19226            final Iterator<PackageSetting> it = sus.packages.iterator();
19227            while (it.hasNext()) {
19228                final PackageSetting ps = it.next();
19229                if (ps.pkg != null) {
19230                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19231                    if (v < vers) vers = v;
19232                }
19233            }
19234            return vers;
19235        } else if (obj instanceof PackageSetting) {
19236            final PackageSetting ps = (PackageSetting) obj;
19237            if (ps.pkg != null) {
19238                return ps.pkg.applicationInfo.targetSdkVersion;
19239            }
19240        }
19241        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19242    }
19243
19244    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19245        final PackageParser.Package p = mPackages.get(packageName);
19246        if (p != null) {
19247            return p.applicationInfo.targetSdkVersion;
19248        }
19249        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19250    }
19251
19252    @Override
19253    public void addPreferredActivity(IntentFilter filter, int match,
19254            ComponentName[] set, ComponentName activity, int userId) {
19255        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19256                "Adding preferred");
19257    }
19258
19259    private void addPreferredActivityInternal(IntentFilter filter, int match,
19260            ComponentName[] set, ComponentName activity, boolean always, int userId,
19261            String opname) {
19262        // writer
19263        int callingUid = Binder.getCallingUid();
19264        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19265                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19266        if (filter.countActions() == 0) {
19267            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19268            return;
19269        }
19270        synchronized (mPackages) {
19271            if (mContext.checkCallingOrSelfPermission(
19272                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19273                    != PackageManager.PERMISSION_GRANTED) {
19274                if (getUidTargetSdkVersionLockedLPr(callingUid)
19275                        < Build.VERSION_CODES.FROYO) {
19276                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19277                            + callingUid);
19278                    return;
19279                }
19280                mContext.enforceCallingOrSelfPermission(
19281                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19282            }
19283
19284            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19285            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19286                    + userId + ":");
19287            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19288            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19289            scheduleWritePackageRestrictionsLocked(userId);
19290            postPreferredActivityChangedBroadcast(userId);
19291        }
19292    }
19293
19294    private void postPreferredActivityChangedBroadcast(int userId) {
19295        mHandler.post(() -> {
19296            final IActivityManager am = ActivityManager.getService();
19297            if (am == null) {
19298                return;
19299            }
19300
19301            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19302            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19303            try {
19304                am.broadcastIntent(null, intent, null, null,
19305                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19306                        null, false, false, userId);
19307            } catch (RemoteException e) {
19308            }
19309        });
19310    }
19311
19312    @Override
19313    public void replacePreferredActivity(IntentFilter filter, int match,
19314            ComponentName[] set, ComponentName activity, int userId) {
19315        if (filter.countActions() != 1) {
19316            throw new IllegalArgumentException(
19317                    "replacePreferredActivity expects filter to have only 1 action.");
19318        }
19319        if (filter.countDataAuthorities() != 0
19320                || filter.countDataPaths() != 0
19321                || filter.countDataSchemes() > 1
19322                || filter.countDataTypes() != 0) {
19323            throw new IllegalArgumentException(
19324                    "replacePreferredActivity expects filter to have no data authorities, " +
19325                    "paths, or types; and at most one scheme.");
19326        }
19327
19328        final int callingUid = Binder.getCallingUid();
19329        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19330                true /* requireFullPermission */, false /* checkShell */,
19331                "replace preferred activity");
19332        synchronized (mPackages) {
19333            if (mContext.checkCallingOrSelfPermission(
19334                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19335                    != PackageManager.PERMISSION_GRANTED) {
19336                if (getUidTargetSdkVersionLockedLPr(callingUid)
19337                        < Build.VERSION_CODES.FROYO) {
19338                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19339                            + Binder.getCallingUid());
19340                    return;
19341                }
19342                mContext.enforceCallingOrSelfPermission(
19343                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19344            }
19345
19346            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19347            if (pir != null) {
19348                // Get all of the existing entries that exactly match this filter.
19349                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19350                if (existing != null && existing.size() == 1) {
19351                    PreferredActivity cur = existing.get(0);
19352                    if (DEBUG_PREFERRED) {
19353                        Slog.i(TAG, "Checking replace of preferred:");
19354                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19355                        if (!cur.mPref.mAlways) {
19356                            Slog.i(TAG, "  -- CUR; not mAlways!");
19357                        } else {
19358                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19359                            Slog.i(TAG, "  -- CUR: mSet="
19360                                    + Arrays.toString(cur.mPref.mSetComponents));
19361                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19362                            Slog.i(TAG, "  -- NEW: mMatch="
19363                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19364                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19365                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19366                        }
19367                    }
19368                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19369                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19370                            && cur.mPref.sameSet(set)) {
19371                        // Setting the preferred activity to what it happens to be already
19372                        if (DEBUG_PREFERRED) {
19373                            Slog.i(TAG, "Replacing with same preferred activity "
19374                                    + cur.mPref.mShortComponent + " for user "
19375                                    + userId + ":");
19376                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19377                        }
19378                        return;
19379                    }
19380                }
19381
19382                if (existing != null) {
19383                    if (DEBUG_PREFERRED) {
19384                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19385                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19386                    }
19387                    for (int i = 0; i < existing.size(); i++) {
19388                        PreferredActivity pa = existing.get(i);
19389                        if (DEBUG_PREFERRED) {
19390                            Slog.i(TAG, "Removing existing preferred activity "
19391                                    + pa.mPref.mComponent + ":");
19392                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19393                        }
19394                        pir.removeFilter(pa);
19395                    }
19396                }
19397            }
19398            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19399                    "Replacing preferred");
19400        }
19401    }
19402
19403    @Override
19404    public void clearPackagePreferredActivities(String packageName) {
19405        final int callingUid = Binder.getCallingUid();
19406        if (getInstantAppPackageName(callingUid) != null) {
19407            return;
19408        }
19409        // writer
19410        synchronized (mPackages) {
19411            PackageParser.Package pkg = mPackages.get(packageName);
19412            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19413                if (mContext.checkCallingOrSelfPermission(
19414                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19415                        != PackageManager.PERMISSION_GRANTED) {
19416                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19417                            < Build.VERSION_CODES.FROYO) {
19418                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19419                                + callingUid);
19420                        return;
19421                    }
19422                    mContext.enforceCallingOrSelfPermission(
19423                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19424                }
19425            }
19426            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19427            if (ps != null
19428                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19429                return;
19430            }
19431            int user = UserHandle.getCallingUserId();
19432            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19433                scheduleWritePackageRestrictionsLocked(user);
19434            }
19435        }
19436    }
19437
19438    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19439    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19440        ArrayList<PreferredActivity> removed = null;
19441        boolean changed = false;
19442        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19443            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19444            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19445            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19446                continue;
19447            }
19448            Iterator<PreferredActivity> it = pir.filterIterator();
19449            while (it.hasNext()) {
19450                PreferredActivity pa = it.next();
19451                // Mark entry for removal only if it matches the package name
19452                // and the entry is of type "always".
19453                if (packageName == null ||
19454                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19455                                && pa.mPref.mAlways)) {
19456                    if (removed == null) {
19457                        removed = new ArrayList<PreferredActivity>();
19458                    }
19459                    removed.add(pa);
19460                }
19461            }
19462            if (removed != null) {
19463                for (int j=0; j<removed.size(); j++) {
19464                    PreferredActivity pa = removed.get(j);
19465                    pir.removeFilter(pa);
19466                }
19467                changed = true;
19468            }
19469        }
19470        if (changed) {
19471            postPreferredActivityChangedBroadcast(userId);
19472        }
19473        return changed;
19474    }
19475
19476    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19477    private void clearIntentFilterVerificationsLPw(int userId) {
19478        final int packageCount = mPackages.size();
19479        for (int i = 0; i < packageCount; i++) {
19480            PackageParser.Package pkg = mPackages.valueAt(i);
19481            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19482        }
19483    }
19484
19485    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19486    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19487        if (userId == UserHandle.USER_ALL) {
19488            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19489                    sUserManager.getUserIds())) {
19490                for (int oneUserId : sUserManager.getUserIds()) {
19491                    scheduleWritePackageRestrictionsLocked(oneUserId);
19492                }
19493            }
19494        } else {
19495            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19496                scheduleWritePackageRestrictionsLocked(userId);
19497            }
19498        }
19499    }
19500
19501    /** Clears state for all users, and touches intent filter verification policy */
19502    void clearDefaultBrowserIfNeeded(String packageName) {
19503        for (int oneUserId : sUserManager.getUserIds()) {
19504            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19505        }
19506    }
19507
19508    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19509        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19510        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19511            if (packageName.equals(defaultBrowserPackageName)) {
19512                setDefaultBrowserPackageName(null, userId);
19513            }
19514        }
19515    }
19516
19517    @Override
19518    public void resetApplicationPreferences(int userId) {
19519        mContext.enforceCallingOrSelfPermission(
19520                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19521        final long identity = Binder.clearCallingIdentity();
19522        // writer
19523        try {
19524            synchronized (mPackages) {
19525                clearPackagePreferredActivitiesLPw(null, userId);
19526                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19527                // TODO: We have to reset the default SMS and Phone. This requires
19528                // significant refactoring to keep all default apps in the package
19529                // manager (cleaner but more work) or have the services provide
19530                // callbacks to the package manager to request a default app reset.
19531                applyFactoryDefaultBrowserLPw(userId);
19532                clearIntentFilterVerificationsLPw(userId);
19533                primeDomainVerificationsLPw(userId);
19534                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19535                scheduleWritePackageRestrictionsLocked(userId);
19536            }
19537            resetNetworkPolicies(userId);
19538        } finally {
19539            Binder.restoreCallingIdentity(identity);
19540        }
19541    }
19542
19543    @Override
19544    public int getPreferredActivities(List<IntentFilter> outFilters,
19545            List<ComponentName> outActivities, String packageName) {
19546        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19547            return 0;
19548        }
19549        int num = 0;
19550        final int userId = UserHandle.getCallingUserId();
19551        // reader
19552        synchronized (mPackages) {
19553            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19554            if (pir != null) {
19555                final Iterator<PreferredActivity> it = pir.filterIterator();
19556                while (it.hasNext()) {
19557                    final PreferredActivity pa = it.next();
19558                    if (packageName == null
19559                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19560                                    && pa.mPref.mAlways)) {
19561                        if (outFilters != null) {
19562                            outFilters.add(new IntentFilter(pa));
19563                        }
19564                        if (outActivities != null) {
19565                            outActivities.add(pa.mPref.mComponent);
19566                        }
19567                    }
19568                }
19569            }
19570        }
19571
19572        return num;
19573    }
19574
19575    @Override
19576    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19577            int userId) {
19578        int callingUid = Binder.getCallingUid();
19579        if (callingUid != Process.SYSTEM_UID) {
19580            throw new SecurityException(
19581                    "addPersistentPreferredActivity can only be run by the system");
19582        }
19583        if (filter.countActions() == 0) {
19584            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19585            return;
19586        }
19587        synchronized (mPackages) {
19588            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19589                    ":");
19590            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19591            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19592                    new PersistentPreferredActivity(filter, activity));
19593            scheduleWritePackageRestrictionsLocked(userId);
19594            postPreferredActivityChangedBroadcast(userId);
19595        }
19596    }
19597
19598    @Override
19599    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19600        int callingUid = Binder.getCallingUid();
19601        if (callingUid != Process.SYSTEM_UID) {
19602            throw new SecurityException(
19603                    "clearPackagePersistentPreferredActivities can only be run by the system");
19604        }
19605        ArrayList<PersistentPreferredActivity> removed = null;
19606        boolean changed = false;
19607        synchronized (mPackages) {
19608            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19609                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19610                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19611                        .valueAt(i);
19612                if (userId != thisUserId) {
19613                    continue;
19614                }
19615                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19616                while (it.hasNext()) {
19617                    PersistentPreferredActivity ppa = it.next();
19618                    // Mark entry for removal only if it matches the package name.
19619                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19620                        if (removed == null) {
19621                            removed = new ArrayList<PersistentPreferredActivity>();
19622                        }
19623                        removed.add(ppa);
19624                    }
19625                }
19626                if (removed != null) {
19627                    for (int j=0; j<removed.size(); j++) {
19628                        PersistentPreferredActivity ppa = removed.get(j);
19629                        ppir.removeFilter(ppa);
19630                    }
19631                    changed = true;
19632                }
19633            }
19634
19635            if (changed) {
19636                scheduleWritePackageRestrictionsLocked(userId);
19637                postPreferredActivityChangedBroadcast(userId);
19638            }
19639        }
19640    }
19641
19642    /**
19643     * Common machinery for picking apart a restored XML blob and passing
19644     * it to a caller-supplied functor to be applied to the running system.
19645     */
19646    private void restoreFromXml(XmlPullParser parser, int userId,
19647            String expectedStartTag, BlobXmlRestorer functor)
19648            throws IOException, XmlPullParserException {
19649        int type;
19650        while ((type = parser.next()) != XmlPullParser.START_TAG
19651                && type != XmlPullParser.END_DOCUMENT) {
19652        }
19653        if (type != XmlPullParser.START_TAG) {
19654            // oops didn't find a start tag?!
19655            if (DEBUG_BACKUP) {
19656                Slog.e(TAG, "Didn't find start tag during restore");
19657            }
19658            return;
19659        }
19660Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19661        // this is supposed to be TAG_PREFERRED_BACKUP
19662        if (!expectedStartTag.equals(parser.getName())) {
19663            if (DEBUG_BACKUP) {
19664                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19665            }
19666            return;
19667        }
19668
19669        // skip interfering stuff, then we're aligned with the backing implementation
19670        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19671Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19672        functor.apply(parser, userId);
19673    }
19674
19675    private interface BlobXmlRestorer {
19676        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19677    }
19678
19679    /**
19680     * Non-Binder method, support for the backup/restore mechanism: write the
19681     * full set of preferred activities in its canonical XML format.  Returns the
19682     * XML output as a byte array, or null if there is none.
19683     */
19684    @Override
19685    public byte[] getPreferredActivityBackup(int userId) {
19686        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19687            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19688        }
19689
19690        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19691        try {
19692            final XmlSerializer serializer = new FastXmlSerializer();
19693            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19694            serializer.startDocument(null, true);
19695            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19696
19697            synchronized (mPackages) {
19698                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19699            }
19700
19701            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19702            serializer.endDocument();
19703            serializer.flush();
19704        } catch (Exception e) {
19705            if (DEBUG_BACKUP) {
19706                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19707            }
19708            return null;
19709        }
19710
19711        return dataStream.toByteArray();
19712    }
19713
19714    @Override
19715    public void restorePreferredActivities(byte[] backup, int userId) {
19716        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19717            throw new SecurityException("Only the system may call restorePreferredActivities()");
19718        }
19719
19720        try {
19721            final XmlPullParser parser = Xml.newPullParser();
19722            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19723            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19724                    new BlobXmlRestorer() {
19725                        @Override
19726                        public void apply(XmlPullParser parser, int userId)
19727                                throws XmlPullParserException, IOException {
19728                            synchronized (mPackages) {
19729                                mSettings.readPreferredActivitiesLPw(parser, userId);
19730                            }
19731                        }
19732                    } );
19733        } catch (Exception e) {
19734            if (DEBUG_BACKUP) {
19735                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19736            }
19737        }
19738    }
19739
19740    /**
19741     * Non-Binder method, support for the backup/restore mechanism: write the
19742     * default browser (etc) settings in its canonical XML format.  Returns the default
19743     * browser XML representation as a byte array, or null if there is none.
19744     */
19745    @Override
19746    public byte[] getDefaultAppsBackup(int userId) {
19747        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19748            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19749        }
19750
19751        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19752        try {
19753            final XmlSerializer serializer = new FastXmlSerializer();
19754            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19755            serializer.startDocument(null, true);
19756            serializer.startTag(null, TAG_DEFAULT_APPS);
19757
19758            synchronized (mPackages) {
19759                mSettings.writeDefaultAppsLPr(serializer, userId);
19760            }
19761
19762            serializer.endTag(null, TAG_DEFAULT_APPS);
19763            serializer.endDocument();
19764            serializer.flush();
19765        } catch (Exception e) {
19766            if (DEBUG_BACKUP) {
19767                Slog.e(TAG, "Unable to write default apps for backup", e);
19768            }
19769            return null;
19770        }
19771
19772        return dataStream.toByteArray();
19773    }
19774
19775    @Override
19776    public void restoreDefaultApps(byte[] backup, int userId) {
19777        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19778            throw new SecurityException("Only the system may call restoreDefaultApps()");
19779        }
19780
19781        try {
19782            final XmlPullParser parser = Xml.newPullParser();
19783            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19784            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19785                    new BlobXmlRestorer() {
19786                        @Override
19787                        public void apply(XmlPullParser parser, int userId)
19788                                throws XmlPullParserException, IOException {
19789                            synchronized (mPackages) {
19790                                mSettings.readDefaultAppsLPw(parser, userId);
19791                            }
19792                        }
19793                    } );
19794        } catch (Exception e) {
19795            if (DEBUG_BACKUP) {
19796                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19797            }
19798        }
19799    }
19800
19801    @Override
19802    public byte[] getIntentFilterVerificationBackup(int userId) {
19803        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19804            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19805        }
19806
19807        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19808        try {
19809            final XmlSerializer serializer = new FastXmlSerializer();
19810            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19811            serializer.startDocument(null, true);
19812            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19813
19814            synchronized (mPackages) {
19815                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19816            }
19817
19818            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19819            serializer.endDocument();
19820            serializer.flush();
19821        } catch (Exception e) {
19822            if (DEBUG_BACKUP) {
19823                Slog.e(TAG, "Unable to write default apps for backup", e);
19824            }
19825            return null;
19826        }
19827
19828        return dataStream.toByteArray();
19829    }
19830
19831    @Override
19832    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19833        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19834            throw new SecurityException("Only the system may call restorePreferredActivities()");
19835        }
19836
19837        try {
19838            final XmlPullParser parser = Xml.newPullParser();
19839            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19840            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19841                    new BlobXmlRestorer() {
19842                        @Override
19843                        public void apply(XmlPullParser parser, int userId)
19844                                throws XmlPullParserException, IOException {
19845                            synchronized (mPackages) {
19846                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19847                                mSettings.writeLPr();
19848                            }
19849                        }
19850                    } );
19851        } catch (Exception e) {
19852            if (DEBUG_BACKUP) {
19853                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19854            }
19855        }
19856    }
19857
19858    @Override
19859    public byte[] getPermissionGrantBackup(int userId) {
19860        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19861            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19862        }
19863
19864        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19865        try {
19866            final XmlSerializer serializer = new FastXmlSerializer();
19867            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19868            serializer.startDocument(null, true);
19869            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19870
19871            synchronized (mPackages) {
19872                serializeRuntimePermissionGrantsLPr(serializer, userId);
19873            }
19874
19875            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19876            serializer.endDocument();
19877            serializer.flush();
19878        } catch (Exception e) {
19879            if (DEBUG_BACKUP) {
19880                Slog.e(TAG, "Unable to write default apps for backup", e);
19881            }
19882            return null;
19883        }
19884
19885        return dataStream.toByteArray();
19886    }
19887
19888    @Override
19889    public void restorePermissionGrants(byte[] backup, int userId) {
19890        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19891            throw new SecurityException("Only the system may call restorePermissionGrants()");
19892        }
19893
19894        try {
19895            final XmlPullParser parser = Xml.newPullParser();
19896            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19897            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19898                    new BlobXmlRestorer() {
19899                        @Override
19900                        public void apply(XmlPullParser parser, int userId)
19901                                throws XmlPullParserException, IOException {
19902                            synchronized (mPackages) {
19903                                processRestoredPermissionGrantsLPr(parser, userId);
19904                            }
19905                        }
19906                    } );
19907        } catch (Exception e) {
19908            if (DEBUG_BACKUP) {
19909                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19910            }
19911        }
19912    }
19913
19914    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19915            throws IOException {
19916        serializer.startTag(null, TAG_ALL_GRANTS);
19917
19918        final int N = mSettings.mPackages.size();
19919        for (int i = 0; i < N; i++) {
19920            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19921            boolean pkgGrantsKnown = false;
19922
19923            PermissionsState packagePerms = ps.getPermissionsState();
19924
19925            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19926                final int grantFlags = state.getFlags();
19927                // only look at grants that are not system/policy fixed
19928                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19929                    final boolean isGranted = state.isGranted();
19930                    // And only back up the user-twiddled state bits
19931                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19932                        final String packageName = mSettings.mPackages.keyAt(i);
19933                        if (!pkgGrantsKnown) {
19934                            serializer.startTag(null, TAG_GRANT);
19935                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19936                            pkgGrantsKnown = true;
19937                        }
19938
19939                        final boolean userSet =
19940                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19941                        final boolean userFixed =
19942                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19943                        final boolean revoke =
19944                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19945
19946                        serializer.startTag(null, TAG_PERMISSION);
19947                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19948                        if (isGranted) {
19949                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19950                        }
19951                        if (userSet) {
19952                            serializer.attribute(null, ATTR_USER_SET, "true");
19953                        }
19954                        if (userFixed) {
19955                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19956                        }
19957                        if (revoke) {
19958                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19959                        }
19960                        serializer.endTag(null, TAG_PERMISSION);
19961                    }
19962                }
19963            }
19964
19965            if (pkgGrantsKnown) {
19966                serializer.endTag(null, TAG_GRANT);
19967            }
19968        }
19969
19970        serializer.endTag(null, TAG_ALL_GRANTS);
19971    }
19972
19973    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19974            throws XmlPullParserException, IOException {
19975        String pkgName = null;
19976        int outerDepth = parser.getDepth();
19977        int type;
19978        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19979                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19980            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19981                continue;
19982            }
19983
19984            final String tagName = parser.getName();
19985            if (tagName.equals(TAG_GRANT)) {
19986                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19987                if (DEBUG_BACKUP) {
19988                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19989                }
19990            } else if (tagName.equals(TAG_PERMISSION)) {
19991
19992                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19993                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19994
19995                int newFlagSet = 0;
19996                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19997                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19998                }
19999                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20000                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20001                }
20002                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20003                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20004                }
20005                if (DEBUG_BACKUP) {
20006                    Slog.v(TAG, "  + Restoring grant:"
20007                            + " pkg=" + pkgName
20008                            + " perm=" + permName
20009                            + " granted=" + isGranted
20010                            + " bits=0x" + Integer.toHexString(newFlagSet));
20011                }
20012                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20013                if (ps != null) {
20014                    // Already installed so we apply the grant immediately
20015                    if (DEBUG_BACKUP) {
20016                        Slog.v(TAG, "        + already installed; applying");
20017                    }
20018                    PermissionsState perms = ps.getPermissionsState();
20019                    BasePermission bp =
20020                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20021                    if (bp != null) {
20022                        if (isGranted) {
20023                            perms.grantRuntimePermission(bp, userId);
20024                        }
20025                        if (newFlagSet != 0) {
20026                            perms.updatePermissionFlags(
20027                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20028                        }
20029                    }
20030                } else {
20031                    // Need to wait for post-restore install to apply the grant
20032                    if (DEBUG_BACKUP) {
20033                        Slog.v(TAG, "        - not yet installed; saving for later");
20034                    }
20035                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20036                            isGranted, newFlagSet, userId);
20037                }
20038            } else {
20039                PackageManagerService.reportSettingsProblem(Log.WARN,
20040                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20041                XmlUtils.skipCurrentTag(parser);
20042            }
20043        }
20044
20045        scheduleWriteSettingsLocked();
20046        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20047    }
20048
20049    @Override
20050    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20051            int sourceUserId, int targetUserId, int flags) {
20052        mContext.enforceCallingOrSelfPermission(
20053                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20054        int callingUid = Binder.getCallingUid();
20055        enforceOwnerRights(ownerPackage, callingUid);
20056        PackageManagerServiceUtils.enforceShellRestriction(
20057                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20058        if (intentFilter.countActions() == 0) {
20059            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20060            return;
20061        }
20062        synchronized (mPackages) {
20063            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20064                    ownerPackage, targetUserId, flags);
20065            CrossProfileIntentResolver resolver =
20066                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20067            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20068            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20069            if (existing != null) {
20070                int size = existing.size();
20071                for (int i = 0; i < size; i++) {
20072                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20073                        return;
20074                    }
20075                }
20076            }
20077            resolver.addFilter(newFilter);
20078            scheduleWritePackageRestrictionsLocked(sourceUserId);
20079        }
20080    }
20081
20082    @Override
20083    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20084        mContext.enforceCallingOrSelfPermission(
20085                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20086        final int callingUid = Binder.getCallingUid();
20087        enforceOwnerRights(ownerPackage, callingUid);
20088        PackageManagerServiceUtils.enforceShellRestriction(
20089                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20090        synchronized (mPackages) {
20091            CrossProfileIntentResolver resolver =
20092                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20093            ArraySet<CrossProfileIntentFilter> set =
20094                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20095            for (CrossProfileIntentFilter filter : set) {
20096                if (filter.getOwnerPackage().equals(ownerPackage)) {
20097                    resolver.removeFilter(filter);
20098                }
20099            }
20100            scheduleWritePackageRestrictionsLocked(sourceUserId);
20101        }
20102    }
20103
20104    // Enforcing that callingUid is owning pkg on userId
20105    private void enforceOwnerRights(String pkg, int callingUid) {
20106        // The system owns everything.
20107        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20108            return;
20109        }
20110        final int callingUserId = UserHandle.getUserId(callingUid);
20111        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20112        if (pi == null) {
20113            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20114                    + callingUserId);
20115        }
20116        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20117            throw new SecurityException("Calling uid " + callingUid
20118                    + " does not own package " + pkg);
20119        }
20120    }
20121
20122    @Override
20123    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20124        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20125            return null;
20126        }
20127        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20128    }
20129
20130    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20131        UserManagerService ums = UserManagerService.getInstance();
20132        if (ums != null) {
20133            final UserInfo parent = ums.getProfileParent(userId);
20134            final int launcherUid = (parent != null) ? parent.id : userId;
20135            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20136            if (launcherComponent != null) {
20137                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20138                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20139                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20140                        .setPackage(launcherComponent.getPackageName());
20141                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20142            }
20143        }
20144    }
20145
20146    /**
20147     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20148     * then reports the most likely home activity or null if there are more than one.
20149     */
20150    private ComponentName getDefaultHomeActivity(int userId) {
20151        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20152        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20153        if (cn != null) {
20154            return cn;
20155        }
20156
20157        // Find the launcher with the highest priority and return that component if there are no
20158        // other home activity with the same priority.
20159        int lastPriority = Integer.MIN_VALUE;
20160        ComponentName lastComponent = null;
20161        final int size = allHomeCandidates.size();
20162        for (int i = 0; i < size; i++) {
20163            final ResolveInfo ri = allHomeCandidates.get(i);
20164            if (ri.priority > lastPriority) {
20165                lastComponent = ri.activityInfo.getComponentName();
20166                lastPriority = ri.priority;
20167            } else if (ri.priority == lastPriority) {
20168                // Two components found with same priority.
20169                lastComponent = null;
20170            }
20171        }
20172        return lastComponent;
20173    }
20174
20175    private Intent getHomeIntent() {
20176        Intent intent = new Intent(Intent.ACTION_MAIN);
20177        intent.addCategory(Intent.CATEGORY_HOME);
20178        intent.addCategory(Intent.CATEGORY_DEFAULT);
20179        return intent;
20180    }
20181
20182    private IntentFilter getHomeFilter() {
20183        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20184        filter.addCategory(Intent.CATEGORY_HOME);
20185        filter.addCategory(Intent.CATEGORY_DEFAULT);
20186        return filter;
20187    }
20188
20189    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20190            int userId) {
20191        Intent intent  = getHomeIntent();
20192        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20193                PackageManager.GET_META_DATA, userId);
20194        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20195                true, false, false, userId);
20196
20197        allHomeCandidates.clear();
20198        if (list != null) {
20199            for (ResolveInfo ri : list) {
20200                allHomeCandidates.add(ri);
20201            }
20202        }
20203        return (preferred == null || preferred.activityInfo == null)
20204                ? null
20205                : new ComponentName(preferred.activityInfo.packageName,
20206                        preferred.activityInfo.name);
20207    }
20208
20209    @Override
20210    public void setHomeActivity(ComponentName comp, int userId) {
20211        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20212            return;
20213        }
20214        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20215        getHomeActivitiesAsUser(homeActivities, userId);
20216
20217        boolean found = false;
20218
20219        final int size = homeActivities.size();
20220        final ComponentName[] set = new ComponentName[size];
20221        for (int i = 0; i < size; i++) {
20222            final ResolveInfo candidate = homeActivities.get(i);
20223            final ActivityInfo info = candidate.activityInfo;
20224            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20225            set[i] = activityName;
20226            if (!found && activityName.equals(comp)) {
20227                found = true;
20228            }
20229        }
20230        if (!found) {
20231            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20232                    + userId);
20233        }
20234        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20235                set, comp, userId);
20236    }
20237
20238    private @Nullable String getSetupWizardPackageName() {
20239        final Intent intent = new Intent(Intent.ACTION_MAIN);
20240        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20241
20242        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20243                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20244                        | MATCH_DISABLED_COMPONENTS,
20245                UserHandle.myUserId());
20246        if (matches.size() == 1) {
20247            return matches.get(0).getComponentInfo().packageName;
20248        } else {
20249            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20250                    + ": matches=" + matches);
20251            return null;
20252        }
20253    }
20254
20255    private @Nullable String getStorageManagerPackageName() {
20256        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20257
20258        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20259                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20260                        | MATCH_DISABLED_COMPONENTS,
20261                UserHandle.myUserId());
20262        if (matches.size() == 1) {
20263            return matches.get(0).getComponentInfo().packageName;
20264        } else {
20265            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20266                    + matches.size() + ": matches=" + matches);
20267            return null;
20268        }
20269    }
20270
20271    @Override
20272    public void setApplicationEnabledSetting(String appPackageName,
20273            int newState, int flags, int userId, String callingPackage) {
20274        if (!sUserManager.exists(userId)) return;
20275        if (callingPackage == null) {
20276            callingPackage = Integer.toString(Binder.getCallingUid());
20277        }
20278        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20279    }
20280
20281    @Override
20282    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20283        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20284        synchronized (mPackages) {
20285            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20286            if (pkgSetting != null) {
20287                pkgSetting.setUpdateAvailable(updateAvailable);
20288            }
20289        }
20290    }
20291
20292    @Override
20293    public void setComponentEnabledSetting(ComponentName componentName,
20294            int newState, int flags, int userId) {
20295        if (!sUserManager.exists(userId)) return;
20296        setEnabledSetting(componentName.getPackageName(),
20297                componentName.getClassName(), newState, flags, userId, null);
20298    }
20299
20300    private void setEnabledSetting(final String packageName, String className, int newState,
20301            final int flags, int userId, String callingPackage) {
20302        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20303              || newState == COMPONENT_ENABLED_STATE_ENABLED
20304              || newState == COMPONENT_ENABLED_STATE_DISABLED
20305              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20306              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20307            throw new IllegalArgumentException("Invalid new component state: "
20308                    + newState);
20309        }
20310        PackageSetting pkgSetting;
20311        final int callingUid = Binder.getCallingUid();
20312        final int permission;
20313        if (callingUid == Process.SYSTEM_UID) {
20314            permission = PackageManager.PERMISSION_GRANTED;
20315        } else {
20316            permission = mContext.checkCallingOrSelfPermission(
20317                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20318        }
20319        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20320                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20321        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20322        boolean sendNow = false;
20323        boolean isApp = (className == null);
20324        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20325        String componentName = isApp ? packageName : className;
20326        int packageUid = -1;
20327        ArrayList<String> components;
20328
20329        // reader
20330        synchronized (mPackages) {
20331            pkgSetting = mSettings.mPackages.get(packageName);
20332            if (pkgSetting == null) {
20333                if (!isCallerInstantApp) {
20334                    if (className == null) {
20335                        throw new IllegalArgumentException("Unknown package: " + packageName);
20336                    }
20337                    throw new IllegalArgumentException(
20338                            "Unknown component: " + packageName + "/" + className);
20339                } else {
20340                    // throw SecurityException to prevent leaking package information
20341                    throw new SecurityException(
20342                            "Attempt to change component state; "
20343                            + "pid=" + Binder.getCallingPid()
20344                            + ", uid=" + callingUid
20345                            + (className == null
20346                                    ? ", package=" + packageName
20347                                    : ", component=" + packageName + "/" + className));
20348                }
20349            }
20350        }
20351
20352        // Limit who can change which apps
20353        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20354            // Don't allow apps that don't have permission to modify other apps
20355            if (!allowedByPermission
20356                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20357                throw new SecurityException(
20358                        "Attempt to change component state; "
20359                        + "pid=" + Binder.getCallingPid()
20360                        + ", uid=" + callingUid
20361                        + (className == null
20362                                ? ", package=" + packageName
20363                                : ", component=" + packageName + "/" + className));
20364            }
20365            // Don't allow changing protected packages.
20366            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20367                throw new SecurityException("Cannot disable a protected package: " + packageName);
20368            }
20369        }
20370
20371        synchronized (mPackages) {
20372            if (callingUid == Process.SHELL_UID
20373                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20374                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20375                // unless it is a test package.
20376                int oldState = pkgSetting.getEnabled(userId);
20377                if (className == null
20378                        &&
20379                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20380                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20381                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20382                        &&
20383                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20384                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20385                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20386                    // ok
20387                } else {
20388                    throw new SecurityException(
20389                            "Shell cannot change component state for " + packageName + "/"
20390                                    + className + " to " + newState);
20391                }
20392            }
20393        }
20394        if (className == null) {
20395            // We're dealing with an application/package level state change
20396            synchronized (mPackages) {
20397                if (pkgSetting.getEnabled(userId) == newState) {
20398                    // Nothing to do
20399                    return;
20400                }
20401            }
20402            // If we're enabling a system stub, there's a little more work to do.
20403            // Prior to enabling the package, we need to decompress the APK(s) to the
20404            // data partition and then replace the version on the system partition.
20405            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20406            final boolean isSystemStub = deletedPkg.isStub
20407                    && deletedPkg.isSystem();
20408            if (isSystemStub
20409                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20410                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20411                final File codePath = decompressPackage(deletedPkg);
20412                if (codePath == null) {
20413                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20414                    return;
20415                }
20416                // TODO remove direct parsing of the package object during internal cleanup
20417                // of scan package
20418                // We need to call parse directly here for no other reason than we need
20419                // the new package in order to disable the old one [we use the information
20420                // for some internal optimization to optionally create a new package setting
20421                // object on replace]. However, we can't get the package from the scan
20422                // because the scan modifies live structures and we need to remove the
20423                // old [system] package from the system before a scan can be attempted.
20424                // Once scan is indempotent we can remove this parse and use the package
20425                // object we scanned, prior to adding it to package settings.
20426                final PackageParser pp = new PackageParser();
20427                pp.setSeparateProcesses(mSeparateProcesses);
20428                pp.setDisplayMetrics(mMetrics);
20429                pp.setCallback(mPackageParserCallback);
20430                final PackageParser.Package tmpPkg;
20431                try {
20432                    final @ParseFlags int parseFlags = mDefParseFlags
20433                            | PackageParser.PARSE_MUST_BE_APK
20434                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20435                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20436                } catch (PackageParserException e) {
20437                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20438                    return;
20439                }
20440                synchronized (mInstallLock) {
20441                    // Disable the stub and remove any package entries
20442                    removePackageLI(deletedPkg, true);
20443                    synchronized (mPackages) {
20444                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20445                    }
20446                    final PackageParser.Package pkg;
20447                    try (PackageFreezer freezer =
20448                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20449                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20450                                | PackageParser.PARSE_ENFORCE_CODE;
20451                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20452                                0 /*currentTime*/, null /*user*/);
20453                        prepareAppDataAfterInstallLIF(pkg);
20454                        synchronized (mPackages) {
20455                            try {
20456                                updateSharedLibrariesLPr(pkg, null);
20457                            } catch (PackageManagerException e) {
20458                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20459                            }
20460                            mPermissionManager.updatePermissions(
20461                                    pkg.packageName, pkg, true, mPackages.values(),
20462                                    mPermissionCallback);
20463                            mSettings.writeLPr();
20464                        }
20465                    } catch (PackageManagerException e) {
20466                        // Whoops! Something went wrong; try to roll back to the stub
20467                        Slog.w(TAG, "Failed to install compressed system package:"
20468                                + pkgSetting.name, e);
20469                        // Remove the failed install
20470                        removeCodePathLI(codePath);
20471
20472                        // Install the system package
20473                        try (PackageFreezer freezer =
20474                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20475                            synchronized (mPackages) {
20476                                // NOTE: The system package always needs to be enabled; even
20477                                // if it's for a compressed stub. If we don't, installing the
20478                                // system package fails during scan [scanning checks the disabled
20479                                // packages]. We will reverse this later, after we've "installed"
20480                                // the stub.
20481                                // This leaves us in a fragile state; the stub should never be
20482                                // enabled, so, cross your fingers and hope nothing goes wrong
20483                                // until we can disable the package later.
20484                                enableSystemPackageLPw(deletedPkg);
20485                            }
20486                            installPackageFromSystemLIF(deletedPkg.codePath,
20487                                    false /*isPrivileged*/, null /*allUserHandles*/,
20488                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20489                                    true /*writeSettings*/);
20490                        } catch (PackageManagerException pme) {
20491                            Slog.w(TAG, "Failed to restore system package:"
20492                                    + deletedPkg.packageName, pme);
20493                        } finally {
20494                            synchronized (mPackages) {
20495                                mSettings.disableSystemPackageLPw(
20496                                        deletedPkg.packageName, true /*replaced*/);
20497                                mSettings.writeLPr();
20498                            }
20499                        }
20500                        return;
20501                    }
20502                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20503                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20504                    mDexManager.notifyPackageUpdated(pkg.packageName,
20505                            pkg.baseCodePath, pkg.splitCodePaths);
20506                }
20507            }
20508            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20509                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20510                // Don't care about who enables an app.
20511                callingPackage = null;
20512            }
20513            synchronized (mPackages) {
20514                pkgSetting.setEnabled(newState, userId, callingPackage);
20515            }
20516        } else {
20517            synchronized (mPackages) {
20518                // We're dealing with a component level state change
20519                // First, verify that this is a valid class name.
20520                PackageParser.Package pkg = pkgSetting.pkg;
20521                if (pkg == null || !pkg.hasComponentClassName(className)) {
20522                    if (pkg != null &&
20523                            pkg.applicationInfo.targetSdkVersion >=
20524                                    Build.VERSION_CODES.JELLY_BEAN) {
20525                        throw new IllegalArgumentException("Component class " + className
20526                                + " does not exist in " + packageName);
20527                    } else {
20528                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20529                                + className + " does not exist in " + packageName);
20530                    }
20531                }
20532                switch (newState) {
20533                    case COMPONENT_ENABLED_STATE_ENABLED:
20534                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20535                            return;
20536                        }
20537                        break;
20538                    case COMPONENT_ENABLED_STATE_DISABLED:
20539                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20540                            return;
20541                        }
20542                        break;
20543                    case COMPONENT_ENABLED_STATE_DEFAULT:
20544                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20545                            return;
20546                        }
20547                        break;
20548                    default:
20549                        Slog.e(TAG, "Invalid new component state: " + newState);
20550                        return;
20551                }
20552            }
20553        }
20554        synchronized (mPackages) {
20555            scheduleWritePackageRestrictionsLocked(userId);
20556            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20557            final long callingId = Binder.clearCallingIdentity();
20558            try {
20559                updateInstantAppInstallerLocked(packageName);
20560            } finally {
20561                Binder.restoreCallingIdentity(callingId);
20562            }
20563            components = mPendingBroadcasts.get(userId, packageName);
20564            final boolean newPackage = components == null;
20565            if (newPackage) {
20566                components = new ArrayList<String>();
20567            }
20568            if (!components.contains(componentName)) {
20569                components.add(componentName);
20570            }
20571            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20572                sendNow = true;
20573                // Purge entry from pending broadcast list if another one exists already
20574                // since we are sending one right away.
20575                mPendingBroadcasts.remove(userId, packageName);
20576            } else {
20577                if (newPackage) {
20578                    mPendingBroadcasts.put(userId, packageName, components);
20579                }
20580                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20581                    // Schedule a message
20582                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20583                }
20584            }
20585        }
20586
20587        long callingId = Binder.clearCallingIdentity();
20588        try {
20589            if (sendNow) {
20590                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20591                sendPackageChangedBroadcast(packageName,
20592                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20593            }
20594        } finally {
20595            Binder.restoreCallingIdentity(callingId);
20596        }
20597    }
20598
20599    @Override
20600    public void flushPackageRestrictionsAsUser(int userId) {
20601        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20602            return;
20603        }
20604        if (!sUserManager.exists(userId)) {
20605            return;
20606        }
20607        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20608                false /* checkShell */, "flushPackageRestrictions");
20609        synchronized (mPackages) {
20610            mSettings.writePackageRestrictionsLPr(userId);
20611            mDirtyUsers.remove(userId);
20612            if (mDirtyUsers.isEmpty()) {
20613                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20614            }
20615        }
20616    }
20617
20618    private void sendPackageChangedBroadcast(String packageName,
20619            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20620        if (DEBUG_INSTALL)
20621            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20622                    + componentNames);
20623        Bundle extras = new Bundle(4);
20624        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20625        String nameList[] = new String[componentNames.size()];
20626        componentNames.toArray(nameList);
20627        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20628        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20629        extras.putInt(Intent.EXTRA_UID, packageUid);
20630        // If this is not reporting a change of the overall package, then only send it
20631        // to registered receivers.  We don't want to launch a swath of apps for every
20632        // little component state change.
20633        final int flags = !componentNames.contains(packageName)
20634                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20635        final int userId = UserHandle.getUserId(packageUid);
20636        final boolean isInstantApp = isInstantApp(packageName, userId);
20637        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20638        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20639        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20640                userIds, instantUserIds);
20641    }
20642
20643    @Override
20644    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20645        if (!sUserManager.exists(userId)) return;
20646        final int callingUid = Binder.getCallingUid();
20647        if (getInstantAppPackageName(callingUid) != null) {
20648            return;
20649        }
20650        final int permission = mContext.checkCallingOrSelfPermission(
20651                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20652        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20653        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20654                true /* requireFullPermission */, true /* checkShell */, "stop package");
20655        // writer
20656        synchronized (mPackages) {
20657            final PackageSetting ps = mSettings.mPackages.get(packageName);
20658            if (!filterAppAccessLPr(ps, callingUid, userId)
20659                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20660                            allowedByPermission, callingUid, userId)) {
20661                scheduleWritePackageRestrictionsLocked(userId);
20662            }
20663        }
20664    }
20665
20666    @Override
20667    public String getInstallerPackageName(String packageName) {
20668        final int callingUid = Binder.getCallingUid();
20669        if (getInstantAppPackageName(callingUid) != null) {
20670            return null;
20671        }
20672        // reader
20673        synchronized (mPackages) {
20674            final PackageSetting ps = mSettings.mPackages.get(packageName);
20675            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20676                return null;
20677            }
20678            return mSettings.getInstallerPackageNameLPr(packageName);
20679        }
20680    }
20681
20682    public boolean isOrphaned(String packageName) {
20683        // reader
20684        synchronized (mPackages) {
20685            return mSettings.isOrphaned(packageName);
20686        }
20687    }
20688
20689    @Override
20690    public int getApplicationEnabledSetting(String packageName, int userId) {
20691        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20692        int callingUid = Binder.getCallingUid();
20693        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20694                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20695        // reader
20696        synchronized (mPackages) {
20697            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20698                return COMPONENT_ENABLED_STATE_DISABLED;
20699            }
20700            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20701        }
20702    }
20703
20704    @Override
20705    public int getComponentEnabledSetting(ComponentName component, int userId) {
20706        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20707        int callingUid = Binder.getCallingUid();
20708        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20709                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20710        synchronized (mPackages) {
20711            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20712                    component, TYPE_UNKNOWN, userId)) {
20713                return COMPONENT_ENABLED_STATE_DISABLED;
20714            }
20715            return mSettings.getComponentEnabledSettingLPr(component, userId);
20716        }
20717    }
20718
20719    @Override
20720    public void enterSafeMode() {
20721        enforceSystemOrRoot("Only the system can request entering safe mode");
20722
20723        if (!mSystemReady) {
20724            mSafeMode = true;
20725        }
20726    }
20727
20728    @Override
20729    public void systemReady() {
20730        enforceSystemOrRoot("Only the system can claim the system is ready");
20731
20732        mSystemReady = true;
20733        final ContentResolver resolver = mContext.getContentResolver();
20734        ContentObserver co = new ContentObserver(mHandler) {
20735            @Override
20736            public void onChange(boolean selfChange) {
20737                mWebInstantAppsDisabled =
20738                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20739                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20740            }
20741        };
20742        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20743                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20744                false, co, UserHandle.USER_SYSTEM);
20745        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20746                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20747        co.onChange(true);
20748
20749        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20750        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20751        // it is done.
20752        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20753            @Override
20754            public void onChange(boolean selfChange) {
20755                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20756                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20757                        oobEnabled == 1 ? "true" : "false");
20758            }
20759        };
20760        mContext.getContentResolver().registerContentObserver(
20761                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20762                UserHandle.USER_SYSTEM);
20763        // At boot, restore the value from the setting, which persists across reboot.
20764        privAppOobObserver.onChange(true);
20765
20766        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20767        // disabled after already being started.
20768        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20769                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20770
20771        // Read the compatibilty setting when the system is ready.
20772        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20773                mContext.getContentResolver(),
20774                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20775        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20776        if (DEBUG_SETTINGS) {
20777            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20778        }
20779
20780        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20781
20782        synchronized (mPackages) {
20783            // Verify that all of the preferred activity components actually
20784            // exist.  It is possible for applications to be updated and at
20785            // that point remove a previously declared activity component that
20786            // had been set as a preferred activity.  We try to clean this up
20787            // the next time we encounter that preferred activity, but it is
20788            // possible for the user flow to never be able to return to that
20789            // situation so here we do a sanity check to make sure we haven't
20790            // left any junk around.
20791            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20792            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20793                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20794                removed.clear();
20795                for (PreferredActivity pa : pir.filterSet()) {
20796                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20797                        removed.add(pa);
20798                    }
20799                }
20800                if (removed.size() > 0) {
20801                    for (int r=0; r<removed.size(); r++) {
20802                        PreferredActivity pa = removed.get(r);
20803                        Slog.w(TAG, "Removing dangling preferred activity: "
20804                                + pa.mPref.mComponent);
20805                        pir.removeFilter(pa);
20806                    }
20807                    mSettings.writePackageRestrictionsLPr(
20808                            mSettings.mPreferredActivities.keyAt(i));
20809                }
20810            }
20811
20812            for (int userId : UserManagerService.getInstance().getUserIds()) {
20813                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20814                    grantPermissionsUserIds = ArrayUtils.appendInt(
20815                            grantPermissionsUserIds, userId);
20816                }
20817            }
20818        }
20819        sUserManager.systemReady();
20820        // If we upgraded grant all default permissions before kicking off.
20821        for (int userId : grantPermissionsUserIds) {
20822            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20823        }
20824
20825        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20826            // If we did not grant default permissions, we preload from this the
20827            // default permission exceptions lazily to ensure we don't hit the
20828            // disk on a new user creation.
20829            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20830        }
20831
20832        // Now that we've scanned all packages, and granted any default
20833        // permissions, ensure permissions are updated. Beware of dragons if you
20834        // try optimizing this.
20835        synchronized (mPackages) {
20836            mPermissionManager.updateAllPermissions(
20837                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20838                    mPermissionCallback);
20839        }
20840
20841        // Kick off any messages waiting for system ready
20842        if (mPostSystemReadyMessages != null) {
20843            for (Message msg : mPostSystemReadyMessages) {
20844                msg.sendToTarget();
20845            }
20846            mPostSystemReadyMessages = null;
20847        }
20848
20849        // Watch for external volumes that come and go over time
20850        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20851        storage.registerListener(mStorageListener);
20852
20853        mInstallerService.systemReady();
20854        mPackageDexOptimizer.systemReady();
20855
20856        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20857                StorageManagerInternal.class);
20858        StorageManagerInternal.addExternalStoragePolicy(
20859                new StorageManagerInternal.ExternalStorageMountPolicy() {
20860            @Override
20861            public int getMountMode(int uid, String packageName) {
20862                if (Process.isIsolated(uid)) {
20863                    return Zygote.MOUNT_EXTERNAL_NONE;
20864                }
20865                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20866                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20867                }
20868                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20869                    return Zygote.MOUNT_EXTERNAL_READ;
20870                }
20871                return Zygote.MOUNT_EXTERNAL_WRITE;
20872            }
20873
20874            @Override
20875            public boolean hasExternalStorage(int uid, String packageName) {
20876                return true;
20877            }
20878        });
20879
20880        // Now that we're mostly running, clean up stale users and apps
20881        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20882        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20883
20884        mPermissionManager.systemReady();
20885    }
20886
20887    public void waitForAppDataPrepared() {
20888        if (mPrepareAppDataFuture == null) {
20889            return;
20890        }
20891        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20892        mPrepareAppDataFuture = null;
20893    }
20894
20895    @Override
20896    public boolean isSafeMode() {
20897        // allow instant applications
20898        return mSafeMode;
20899    }
20900
20901    @Override
20902    public boolean hasSystemUidErrors() {
20903        // allow instant applications
20904        return mHasSystemUidErrors;
20905    }
20906
20907    static String arrayToString(int[] array) {
20908        StringBuffer buf = new StringBuffer(128);
20909        buf.append('[');
20910        if (array != null) {
20911            for (int i=0; i<array.length; i++) {
20912                if (i > 0) buf.append(", ");
20913                buf.append(array[i]);
20914            }
20915        }
20916        buf.append(']');
20917        return buf.toString();
20918    }
20919
20920    @Override
20921    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20922            FileDescriptor err, String[] args, ShellCallback callback,
20923            ResultReceiver resultReceiver) {
20924        (new PackageManagerShellCommand(this)).exec(
20925                this, in, out, err, args, callback, resultReceiver);
20926    }
20927
20928    @Override
20929    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20930        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20931
20932        DumpState dumpState = new DumpState();
20933        boolean fullPreferred = false;
20934        boolean checkin = false;
20935
20936        String packageName = null;
20937        ArraySet<String> permissionNames = null;
20938
20939        int opti = 0;
20940        while (opti < args.length) {
20941            String opt = args[opti];
20942            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20943                break;
20944            }
20945            opti++;
20946
20947            if ("-a".equals(opt)) {
20948                // Right now we only know how to print all.
20949            } else if ("-h".equals(opt)) {
20950                pw.println("Package manager dump options:");
20951                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20952                pw.println("    --checkin: dump for a checkin");
20953                pw.println("    -f: print details of intent filters");
20954                pw.println("    -h: print this help");
20955                pw.println("  cmd may be one of:");
20956                pw.println("    l[ibraries]: list known shared libraries");
20957                pw.println("    f[eatures]: list device features");
20958                pw.println("    k[eysets]: print known keysets");
20959                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20960                pw.println("    perm[issions]: dump permissions");
20961                pw.println("    permission [name ...]: dump declaration and use of given permission");
20962                pw.println("    pref[erred]: print preferred package settings");
20963                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20964                pw.println("    prov[iders]: dump content providers");
20965                pw.println("    p[ackages]: dump installed packages");
20966                pw.println("    s[hared-users]: dump shared user IDs");
20967                pw.println("    m[essages]: print collected runtime messages");
20968                pw.println("    v[erifiers]: print package verifier info");
20969                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20970                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20971                pw.println("    version: print database version info");
20972                pw.println("    write: write current settings now");
20973                pw.println("    installs: details about install sessions");
20974                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20975                pw.println("    dexopt: dump dexopt state");
20976                pw.println("    compiler-stats: dump compiler statistics");
20977                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20978                pw.println("    service-permissions: dump permissions required by services");
20979                pw.println("    <package.name>: info about given package");
20980                return;
20981            } else if ("--checkin".equals(opt)) {
20982                checkin = true;
20983            } else if ("-f".equals(opt)) {
20984                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20985            } else if ("--proto".equals(opt)) {
20986                dumpProto(fd);
20987                return;
20988            } else {
20989                pw.println("Unknown argument: " + opt + "; use -h for help");
20990            }
20991        }
20992
20993        // Is the caller requesting to dump a particular piece of data?
20994        if (opti < args.length) {
20995            String cmd = args[opti];
20996            opti++;
20997            // Is this a package name?
20998            if ("android".equals(cmd) || cmd.contains(".")) {
20999                packageName = cmd;
21000                // When dumping a single package, we always dump all of its
21001                // filter information since the amount of data will be reasonable.
21002                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21003            } else if ("check-permission".equals(cmd)) {
21004                if (opti >= args.length) {
21005                    pw.println("Error: check-permission missing permission argument");
21006                    return;
21007                }
21008                String perm = args[opti];
21009                opti++;
21010                if (opti >= args.length) {
21011                    pw.println("Error: check-permission missing package argument");
21012                    return;
21013                }
21014
21015                String pkg = args[opti];
21016                opti++;
21017                int user = UserHandle.getUserId(Binder.getCallingUid());
21018                if (opti < args.length) {
21019                    try {
21020                        user = Integer.parseInt(args[opti]);
21021                    } catch (NumberFormatException e) {
21022                        pw.println("Error: check-permission user argument is not a number: "
21023                                + args[opti]);
21024                        return;
21025                    }
21026                }
21027
21028                // Normalize package name to handle renamed packages and static libs
21029                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21030
21031                pw.println(checkPermission(perm, pkg, user));
21032                return;
21033            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21034                dumpState.setDump(DumpState.DUMP_LIBS);
21035            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21036                dumpState.setDump(DumpState.DUMP_FEATURES);
21037            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21038                if (opti >= args.length) {
21039                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21040                            | DumpState.DUMP_SERVICE_RESOLVERS
21041                            | DumpState.DUMP_RECEIVER_RESOLVERS
21042                            | DumpState.DUMP_CONTENT_RESOLVERS);
21043                } else {
21044                    while (opti < args.length) {
21045                        String name = args[opti];
21046                        if ("a".equals(name) || "activity".equals(name)) {
21047                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21048                        } else if ("s".equals(name) || "service".equals(name)) {
21049                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21050                        } else if ("r".equals(name) || "receiver".equals(name)) {
21051                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21052                        } else if ("c".equals(name) || "content".equals(name)) {
21053                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21054                        } else {
21055                            pw.println("Error: unknown resolver table type: " + name);
21056                            return;
21057                        }
21058                        opti++;
21059                    }
21060                }
21061            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21062                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21063            } else if ("permission".equals(cmd)) {
21064                if (opti >= args.length) {
21065                    pw.println("Error: permission requires permission name");
21066                    return;
21067                }
21068                permissionNames = new ArraySet<>();
21069                while (opti < args.length) {
21070                    permissionNames.add(args[opti]);
21071                    opti++;
21072                }
21073                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21074                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21075            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21076                dumpState.setDump(DumpState.DUMP_PREFERRED);
21077            } else if ("preferred-xml".equals(cmd)) {
21078                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21079                if (opti < args.length && "--full".equals(args[opti])) {
21080                    fullPreferred = true;
21081                    opti++;
21082                }
21083            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21084                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21085            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21086                dumpState.setDump(DumpState.DUMP_PACKAGES);
21087            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21088                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21089            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21090                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21091            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21092                dumpState.setDump(DumpState.DUMP_MESSAGES);
21093            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21094                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21095            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21096                    || "intent-filter-verifiers".equals(cmd)) {
21097                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21098            } else if ("version".equals(cmd)) {
21099                dumpState.setDump(DumpState.DUMP_VERSION);
21100            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21101                dumpState.setDump(DumpState.DUMP_KEYSETS);
21102            } else if ("installs".equals(cmd)) {
21103                dumpState.setDump(DumpState.DUMP_INSTALLS);
21104            } else if ("frozen".equals(cmd)) {
21105                dumpState.setDump(DumpState.DUMP_FROZEN);
21106            } else if ("volumes".equals(cmd)) {
21107                dumpState.setDump(DumpState.DUMP_VOLUMES);
21108            } else if ("dexopt".equals(cmd)) {
21109                dumpState.setDump(DumpState.DUMP_DEXOPT);
21110            } else if ("compiler-stats".equals(cmd)) {
21111                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21112            } else if ("changes".equals(cmd)) {
21113                dumpState.setDump(DumpState.DUMP_CHANGES);
21114            } else if ("service-permissions".equals(cmd)) {
21115                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21116            } else if ("write".equals(cmd)) {
21117                synchronized (mPackages) {
21118                    mSettings.writeLPr();
21119                    pw.println("Settings written.");
21120                    return;
21121                }
21122            }
21123        }
21124
21125        if (checkin) {
21126            pw.println("vers,1");
21127        }
21128
21129        // reader
21130        synchronized (mPackages) {
21131            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21132                if (!checkin) {
21133                    if (dumpState.onTitlePrinted())
21134                        pw.println();
21135                    pw.println("Database versions:");
21136                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21137                }
21138            }
21139
21140            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21141                if (!checkin) {
21142                    if (dumpState.onTitlePrinted())
21143                        pw.println();
21144                    pw.println("Verifiers:");
21145                    pw.print("  Required: ");
21146                    pw.print(mRequiredVerifierPackage);
21147                    pw.print(" (uid=");
21148                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21149                            UserHandle.USER_SYSTEM));
21150                    pw.println(")");
21151                } else if (mRequiredVerifierPackage != null) {
21152                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21153                    pw.print(",");
21154                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21155                            UserHandle.USER_SYSTEM));
21156                }
21157            }
21158
21159            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21160                    packageName == null) {
21161                if (mIntentFilterVerifierComponent != null) {
21162                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21163                    if (!checkin) {
21164                        if (dumpState.onTitlePrinted())
21165                            pw.println();
21166                        pw.println("Intent Filter Verifier:");
21167                        pw.print("  Using: ");
21168                        pw.print(verifierPackageName);
21169                        pw.print(" (uid=");
21170                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21171                                UserHandle.USER_SYSTEM));
21172                        pw.println(")");
21173                    } else if (verifierPackageName != null) {
21174                        pw.print("ifv,"); pw.print(verifierPackageName);
21175                        pw.print(",");
21176                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21177                                UserHandle.USER_SYSTEM));
21178                    }
21179                } else {
21180                    pw.println();
21181                    pw.println("No Intent Filter Verifier available!");
21182                }
21183            }
21184
21185            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21186                boolean printedHeader = false;
21187                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21188                while (it.hasNext()) {
21189                    String libName = it.next();
21190                    LongSparseArray<SharedLibraryEntry> versionedLib
21191                            = mSharedLibraries.get(libName);
21192                    if (versionedLib == null) {
21193                        continue;
21194                    }
21195                    final int versionCount = versionedLib.size();
21196                    for (int i = 0; i < versionCount; i++) {
21197                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21198                        if (!checkin) {
21199                            if (!printedHeader) {
21200                                if (dumpState.onTitlePrinted())
21201                                    pw.println();
21202                                pw.println("Libraries:");
21203                                printedHeader = true;
21204                            }
21205                            pw.print("  ");
21206                        } else {
21207                            pw.print("lib,");
21208                        }
21209                        pw.print(libEntry.info.getName());
21210                        if (libEntry.info.isStatic()) {
21211                            pw.print(" version=" + libEntry.info.getLongVersion());
21212                        }
21213                        if (!checkin) {
21214                            pw.print(" -> ");
21215                        }
21216                        if (libEntry.path != null) {
21217                            pw.print(" (jar) ");
21218                            pw.print(libEntry.path);
21219                        } else {
21220                            pw.print(" (apk) ");
21221                            pw.print(libEntry.apk);
21222                        }
21223                        pw.println();
21224                    }
21225                }
21226            }
21227
21228            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21229                if (dumpState.onTitlePrinted())
21230                    pw.println();
21231                if (!checkin) {
21232                    pw.println("Features:");
21233                }
21234
21235                synchronized (mAvailableFeatures) {
21236                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21237                        if (checkin) {
21238                            pw.print("feat,");
21239                            pw.print(feat.name);
21240                            pw.print(",");
21241                            pw.println(feat.version);
21242                        } else {
21243                            pw.print("  ");
21244                            pw.print(feat.name);
21245                            if (feat.version > 0) {
21246                                pw.print(" version=");
21247                                pw.print(feat.version);
21248                            }
21249                            pw.println();
21250                        }
21251                    }
21252                }
21253            }
21254
21255            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21256                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21257                        : "Activity Resolver Table:", "  ", packageName,
21258                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21259                    dumpState.setTitlePrinted(true);
21260                }
21261            }
21262            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21263                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21264                        : "Receiver Resolver Table:", "  ", packageName,
21265                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21266                    dumpState.setTitlePrinted(true);
21267                }
21268            }
21269            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21270                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21271                        : "Service Resolver Table:", "  ", packageName,
21272                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21273                    dumpState.setTitlePrinted(true);
21274                }
21275            }
21276            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21277                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21278                        : "Provider Resolver Table:", "  ", packageName,
21279                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21280                    dumpState.setTitlePrinted(true);
21281                }
21282            }
21283
21284            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21285                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21286                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21287                    int user = mSettings.mPreferredActivities.keyAt(i);
21288                    if (pir.dump(pw,
21289                            dumpState.getTitlePrinted()
21290                                ? "\nPreferred Activities User " + user + ":"
21291                                : "Preferred Activities User " + user + ":", "  ",
21292                            packageName, true, false)) {
21293                        dumpState.setTitlePrinted(true);
21294                    }
21295                }
21296            }
21297
21298            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21299                pw.flush();
21300                FileOutputStream fout = new FileOutputStream(fd);
21301                BufferedOutputStream str = new BufferedOutputStream(fout);
21302                XmlSerializer serializer = new FastXmlSerializer();
21303                try {
21304                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21305                    serializer.startDocument(null, true);
21306                    serializer.setFeature(
21307                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21308                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21309                    serializer.endDocument();
21310                    serializer.flush();
21311                } catch (IllegalArgumentException e) {
21312                    pw.println("Failed writing: " + e);
21313                } catch (IllegalStateException e) {
21314                    pw.println("Failed writing: " + e);
21315                } catch (IOException e) {
21316                    pw.println("Failed writing: " + e);
21317                }
21318            }
21319
21320            if (!checkin
21321                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21322                    && packageName == null) {
21323                pw.println();
21324                int count = mSettings.mPackages.size();
21325                if (count == 0) {
21326                    pw.println("No applications!");
21327                    pw.println();
21328                } else {
21329                    final String prefix = "  ";
21330                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21331                    if (allPackageSettings.size() == 0) {
21332                        pw.println("No domain preferred apps!");
21333                        pw.println();
21334                    } else {
21335                        pw.println("App verification status:");
21336                        pw.println();
21337                        count = 0;
21338                        for (PackageSetting ps : allPackageSettings) {
21339                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21340                            if (ivi == null || ivi.getPackageName() == null) continue;
21341                            pw.println(prefix + "Package: " + ivi.getPackageName());
21342                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21343                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21344                            pw.println();
21345                            count++;
21346                        }
21347                        if (count == 0) {
21348                            pw.println(prefix + "No app verification established.");
21349                            pw.println();
21350                        }
21351                        for (int userId : sUserManager.getUserIds()) {
21352                            pw.println("App linkages for user " + userId + ":");
21353                            pw.println();
21354                            count = 0;
21355                            for (PackageSetting ps : allPackageSettings) {
21356                                final long status = ps.getDomainVerificationStatusForUser(userId);
21357                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21358                                        && !DEBUG_DOMAIN_VERIFICATION) {
21359                                    continue;
21360                                }
21361                                pw.println(prefix + "Package: " + ps.name);
21362                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21363                                String statusStr = IntentFilterVerificationInfo.
21364                                        getStatusStringFromValue(status);
21365                                pw.println(prefix + "Status:  " + statusStr);
21366                                pw.println();
21367                                count++;
21368                            }
21369                            if (count == 0) {
21370                                pw.println(prefix + "No configured app linkages.");
21371                                pw.println();
21372                            }
21373                        }
21374                    }
21375                }
21376            }
21377
21378            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21379                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21380            }
21381
21382            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21383                boolean printedSomething = false;
21384                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21385                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21386                        continue;
21387                    }
21388                    if (!printedSomething) {
21389                        if (dumpState.onTitlePrinted())
21390                            pw.println();
21391                        pw.println("Registered ContentProviders:");
21392                        printedSomething = true;
21393                    }
21394                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21395                    pw.print("    "); pw.println(p.toString());
21396                }
21397                printedSomething = false;
21398                for (Map.Entry<String, PackageParser.Provider> entry :
21399                        mProvidersByAuthority.entrySet()) {
21400                    PackageParser.Provider p = entry.getValue();
21401                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21402                        continue;
21403                    }
21404                    if (!printedSomething) {
21405                        if (dumpState.onTitlePrinted())
21406                            pw.println();
21407                        pw.println("ContentProvider Authorities:");
21408                        printedSomething = true;
21409                    }
21410                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21411                    pw.print("    "); pw.println(p.toString());
21412                    if (p.info != null && p.info.applicationInfo != null) {
21413                        final String appInfo = p.info.applicationInfo.toString();
21414                        pw.print("      applicationInfo="); pw.println(appInfo);
21415                    }
21416                }
21417            }
21418
21419            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21420                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21421            }
21422
21423            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21424                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21425            }
21426
21427            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21428                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21429            }
21430
21431            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21432                if (dumpState.onTitlePrinted()) pw.println();
21433                pw.println("Package Changes:");
21434                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21435                final int K = mChangedPackages.size();
21436                for (int i = 0; i < K; i++) {
21437                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21438                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21439                    final int N = changes.size();
21440                    if (N == 0) {
21441                        pw.print("    "); pw.println("No packages changed");
21442                    } else {
21443                        for (int j = 0; j < N; j++) {
21444                            final String pkgName = changes.valueAt(j);
21445                            final int sequenceNumber = changes.keyAt(j);
21446                            pw.print("    ");
21447                            pw.print("seq=");
21448                            pw.print(sequenceNumber);
21449                            pw.print(", package=");
21450                            pw.println(pkgName);
21451                        }
21452                    }
21453                }
21454            }
21455
21456            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21457                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21458            }
21459
21460            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21461                // XXX should handle packageName != null by dumping only install data that
21462                // the given package is involved with.
21463                if (dumpState.onTitlePrinted()) pw.println();
21464
21465                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21466                ipw.println();
21467                ipw.println("Frozen packages:");
21468                ipw.increaseIndent();
21469                if (mFrozenPackages.size() == 0) {
21470                    ipw.println("(none)");
21471                } else {
21472                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21473                        ipw.println(mFrozenPackages.valueAt(i));
21474                    }
21475                }
21476                ipw.decreaseIndent();
21477            }
21478
21479            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21480                if (dumpState.onTitlePrinted()) pw.println();
21481
21482                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21483                ipw.println();
21484                ipw.println("Loaded volumes:");
21485                ipw.increaseIndent();
21486                if (mLoadedVolumes.size() == 0) {
21487                    ipw.println("(none)");
21488                } else {
21489                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21490                        ipw.println(mLoadedVolumes.valueAt(i));
21491                    }
21492                }
21493                ipw.decreaseIndent();
21494            }
21495
21496            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21497                    && packageName == null) {
21498                if (dumpState.onTitlePrinted()) pw.println();
21499                pw.println("Service permissions:");
21500
21501                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21502                while (filterIterator.hasNext()) {
21503                    final ServiceIntentInfo info = filterIterator.next();
21504                    final ServiceInfo serviceInfo = info.service.info;
21505                    final String permission = serviceInfo.permission;
21506                    if (permission != null) {
21507                        pw.print("    ");
21508                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21509                        pw.print(": ");
21510                        pw.println(permission);
21511                    }
21512                }
21513            }
21514
21515            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21516                if (dumpState.onTitlePrinted()) pw.println();
21517                dumpDexoptStateLPr(pw, packageName);
21518            }
21519
21520            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21521                if (dumpState.onTitlePrinted()) pw.println();
21522                dumpCompilerStatsLPr(pw, packageName);
21523            }
21524
21525            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21526                if (dumpState.onTitlePrinted()) pw.println();
21527                mSettings.dumpReadMessagesLPr(pw, dumpState);
21528
21529                pw.println();
21530                pw.println("Package warning messages:");
21531                dumpCriticalInfo(pw, null);
21532            }
21533
21534            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21535                dumpCriticalInfo(pw, "msg,");
21536            }
21537        }
21538
21539        // PackageInstaller should be called outside of mPackages lock
21540        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21541            // XXX should handle packageName != null by dumping only install data that
21542            // the given package is involved with.
21543            if (dumpState.onTitlePrinted()) pw.println();
21544            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21545        }
21546    }
21547
21548    private void dumpProto(FileDescriptor fd) {
21549        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21550
21551        synchronized (mPackages) {
21552            final long requiredVerifierPackageToken =
21553                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21554            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21555            proto.write(
21556                    PackageServiceDumpProto.PackageShortProto.UID,
21557                    getPackageUid(
21558                            mRequiredVerifierPackage,
21559                            MATCH_DEBUG_TRIAGED_MISSING,
21560                            UserHandle.USER_SYSTEM));
21561            proto.end(requiredVerifierPackageToken);
21562
21563            if (mIntentFilterVerifierComponent != null) {
21564                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21565                final long verifierPackageToken =
21566                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21567                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21568                proto.write(
21569                        PackageServiceDumpProto.PackageShortProto.UID,
21570                        getPackageUid(
21571                                verifierPackageName,
21572                                MATCH_DEBUG_TRIAGED_MISSING,
21573                                UserHandle.USER_SYSTEM));
21574                proto.end(verifierPackageToken);
21575            }
21576
21577            dumpSharedLibrariesProto(proto);
21578            dumpFeaturesProto(proto);
21579            mSettings.dumpPackagesProto(proto);
21580            mSettings.dumpSharedUsersProto(proto);
21581            dumpCriticalInfo(proto);
21582        }
21583        proto.flush();
21584    }
21585
21586    private void dumpFeaturesProto(ProtoOutputStream proto) {
21587        synchronized (mAvailableFeatures) {
21588            final int count = mAvailableFeatures.size();
21589            for (int i = 0; i < count; i++) {
21590                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21591            }
21592        }
21593    }
21594
21595    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21596        final int count = mSharedLibraries.size();
21597        for (int i = 0; i < count; i++) {
21598            final String libName = mSharedLibraries.keyAt(i);
21599            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21600            if (versionedLib == null) {
21601                continue;
21602            }
21603            final int versionCount = versionedLib.size();
21604            for (int j = 0; j < versionCount; j++) {
21605                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21606                final long sharedLibraryToken =
21607                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21608                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21609                final boolean isJar = (libEntry.path != null);
21610                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21611                if (isJar) {
21612                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21613                } else {
21614                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21615                }
21616                proto.end(sharedLibraryToken);
21617            }
21618        }
21619    }
21620
21621    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21622        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21623        ipw.println();
21624        ipw.println("Dexopt state:");
21625        ipw.increaseIndent();
21626        Collection<PackageParser.Package> packages = null;
21627        if (packageName != null) {
21628            PackageParser.Package targetPackage = mPackages.get(packageName);
21629            if (targetPackage != null) {
21630                packages = Collections.singletonList(targetPackage);
21631            } else {
21632                ipw.println("Unable to find package: " + packageName);
21633                return;
21634            }
21635        } else {
21636            packages = mPackages.values();
21637        }
21638
21639        for (PackageParser.Package pkg : packages) {
21640            ipw.println("[" + pkg.packageName + "]");
21641            ipw.increaseIndent();
21642            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21643                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21644            ipw.decreaseIndent();
21645        }
21646    }
21647
21648    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21649        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21650        ipw.println();
21651        ipw.println("Compiler stats:");
21652        ipw.increaseIndent();
21653        Collection<PackageParser.Package> packages = null;
21654        if (packageName != null) {
21655            PackageParser.Package targetPackage = mPackages.get(packageName);
21656            if (targetPackage != null) {
21657                packages = Collections.singletonList(targetPackage);
21658            } else {
21659                ipw.println("Unable to find package: " + packageName);
21660                return;
21661            }
21662        } else {
21663            packages = mPackages.values();
21664        }
21665
21666        for (PackageParser.Package pkg : packages) {
21667            ipw.println("[" + pkg.packageName + "]");
21668            ipw.increaseIndent();
21669
21670            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21671            if (stats == null) {
21672                ipw.println("(No recorded stats)");
21673            } else {
21674                stats.dump(ipw);
21675            }
21676            ipw.decreaseIndent();
21677        }
21678    }
21679
21680    private String dumpDomainString(String packageName) {
21681        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21682                .getList();
21683        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21684
21685        ArraySet<String> result = new ArraySet<>();
21686        if (iviList.size() > 0) {
21687            for (IntentFilterVerificationInfo ivi : iviList) {
21688                for (String host : ivi.getDomains()) {
21689                    result.add(host);
21690                }
21691            }
21692        }
21693        if (filters != null && filters.size() > 0) {
21694            for (IntentFilter filter : filters) {
21695                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21696                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21697                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21698                    result.addAll(filter.getHostsList());
21699                }
21700            }
21701        }
21702
21703        StringBuilder sb = new StringBuilder(result.size() * 16);
21704        for (String domain : result) {
21705            if (sb.length() > 0) sb.append(" ");
21706            sb.append(domain);
21707        }
21708        return sb.toString();
21709    }
21710
21711    // ------- apps on sdcard specific code -------
21712    static final boolean DEBUG_SD_INSTALL = false;
21713
21714    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21715
21716    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21717
21718    private boolean mMediaMounted = false;
21719
21720    static String getEncryptKey() {
21721        try {
21722            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21723                    SD_ENCRYPTION_KEYSTORE_NAME);
21724            if (sdEncKey == null) {
21725                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21726                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21727                if (sdEncKey == null) {
21728                    Slog.e(TAG, "Failed to create encryption keys");
21729                    return null;
21730                }
21731            }
21732            return sdEncKey;
21733        } catch (NoSuchAlgorithmException nsae) {
21734            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21735            return null;
21736        } catch (IOException ioe) {
21737            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21738            return null;
21739        }
21740    }
21741
21742    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21743            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21744        final int size = infos.size();
21745        final String[] packageNames = new String[size];
21746        final int[] packageUids = new int[size];
21747        for (int i = 0; i < size; i++) {
21748            final ApplicationInfo info = infos.get(i);
21749            packageNames[i] = info.packageName;
21750            packageUids[i] = info.uid;
21751        }
21752        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21753                finishedReceiver);
21754    }
21755
21756    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21757            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21758        sendResourcesChangedBroadcast(mediaStatus, replacing,
21759                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21760    }
21761
21762    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21763            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21764        int size = pkgList.length;
21765        if (size > 0) {
21766            // Send broadcasts here
21767            Bundle extras = new Bundle();
21768            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21769            if (uidArr != null) {
21770                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21771            }
21772            if (replacing) {
21773                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21774            }
21775            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21776                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21777            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21778        }
21779    }
21780
21781    private void loadPrivatePackages(final VolumeInfo vol) {
21782        mHandler.post(new Runnable() {
21783            @Override
21784            public void run() {
21785                loadPrivatePackagesInner(vol);
21786            }
21787        });
21788    }
21789
21790    private void loadPrivatePackagesInner(VolumeInfo vol) {
21791        final String volumeUuid = vol.fsUuid;
21792        if (TextUtils.isEmpty(volumeUuid)) {
21793            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21794            return;
21795        }
21796
21797        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21798        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21799        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21800
21801        final VersionInfo ver;
21802        final List<PackageSetting> packages;
21803        synchronized (mPackages) {
21804            ver = mSettings.findOrCreateVersion(volumeUuid);
21805            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21806        }
21807
21808        for (PackageSetting ps : packages) {
21809            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21810            synchronized (mInstallLock) {
21811                final PackageParser.Package pkg;
21812                try {
21813                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21814                    loaded.add(pkg.applicationInfo);
21815
21816                } catch (PackageManagerException e) {
21817                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21818                }
21819
21820                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21821                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21822                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21823                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21824                }
21825            }
21826        }
21827
21828        // Reconcile app data for all started/unlocked users
21829        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21830        final UserManager um = mContext.getSystemService(UserManager.class);
21831        UserManagerInternal umInternal = getUserManagerInternal();
21832        for (UserInfo user : um.getUsers()) {
21833            final int flags;
21834            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21835                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21836            } else if (umInternal.isUserRunning(user.id)) {
21837                flags = StorageManager.FLAG_STORAGE_DE;
21838            } else {
21839                continue;
21840            }
21841
21842            try {
21843                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21844                synchronized (mInstallLock) {
21845                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21846                }
21847            } catch (IllegalStateException e) {
21848                // Device was probably ejected, and we'll process that event momentarily
21849                Slog.w(TAG, "Failed to prepare storage: " + e);
21850            }
21851        }
21852
21853        synchronized (mPackages) {
21854            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21855            if (sdkUpdated) {
21856                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21857                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21858            }
21859            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21860                    mPermissionCallback);
21861
21862            // Yay, everything is now upgraded
21863            ver.forceCurrent();
21864
21865            mSettings.writeLPr();
21866        }
21867
21868        for (PackageFreezer freezer : freezers) {
21869            freezer.close();
21870        }
21871
21872        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21873        sendResourcesChangedBroadcast(true, false, loaded, null);
21874        mLoadedVolumes.add(vol.getId());
21875    }
21876
21877    private void unloadPrivatePackages(final VolumeInfo vol) {
21878        mHandler.post(new Runnable() {
21879            @Override
21880            public void run() {
21881                unloadPrivatePackagesInner(vol);
21882            }
21883        });
21884    }
21885
21886    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21887        final String volumeUuid = vol.fsUuid;
21888        if (TextUtils.isEmpty(volumeUuid)) {
21889            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21890            return;
21891        }
21892
21893        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21894        synchronized (mInstallLock) {
21895        synchronized (mPackages) {
21896            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21897            for (PackageSetting ps : packages) {
21898                if (ps.pkg == null) continue;
21899
21900                final ApplicationInfo info = ps.pkg.applicationInfo;
21901                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21902                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21903
21904                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21905                        "unloadPrivatePackagesInner")) {
21906                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21907                            false, null)) {
21908                        unloaded.add(info);
21909                    } else {
21910                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21911                    }
21912                }
21913
21914                // Try very hard to release any references to this package
21915                // so we don't risk the system server being killed due to
21916                // open FDs
21917                AttributeCache.instance().removePackage(ps.name);
21918            }
21919
21920            mSettings.writeLPr();
21921        }
21922        }
21923
21924        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21925        sendResourcesChangedBroadcast(false, false, unloaded, null);
21926        mLoadedVolumes.remove(vol.getId());
21927
21928        // Try very hard to release any references to this path so we don't risk
21929        // the system server being killed due to open FDs
21930        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21931
21932        for (int i = 0; i < 3; i++) {
21933            System.gc();
21934            System.runFinalization();
21935        }
21936    }
21937
21938    private void assertPackageKnown(String volumeUuid, String packageName)
21939            throws PackageManagerException {
21940        synchronized (mPackages) {
21941            // Normalize package name to handle renamed packages
21942            packageName = normalizePackageNameLPr(packageName);
21943
21944            final PackageSetting ps = mSettings.mPackages.get(packageName);
21945            if (ps == null) {
21946                throw new PackageManagerException("Package " + packageName + " is unknown");
21947            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21948                throw new PackageManagerException(
21949                        "Package " + packageName + " found on unknown volume " + volumeUuid
21950                                + "; expected volume " + ps.volumeUuid);
21951            }
21952        }
21953    }
21954
21955    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21956            throws PackageManagerException {
21957        synchronized (mPackages) {
21958            // Normalize package name to handle renamed packages
21959            packageName = normalizePackageNameLPr(packageName);
21960
21961            final PackageSetting ps = mSettings.mPackages.get(packageName);
21962            if (ps == null) {
21963                throw new PackageManagerException("Package " + packageName + " is unknown");
21964            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21965                throw new PackageManagerException(
21966                        "Package " + packageName + " found on unknown volume " + volumeUuid
21967                                + "; expected volume " + ps.volumeUuid);
21968            } else if (!ps.getInstalled(userId)) {
21969                throw new PackageManagerException(
21970                        "Package " + packageName + " not installed for user " + userId);
21971            }
21972        }
21973    }
21974
21975    private List<String> collectAbsoluteCodePaths() {
21976        synchronized (mPackages) {
21977            List<String> codePaths = new ArrayList<>();
21978            final int packageCount = mSettings.mPackages.size();
21979            for (int i = 0; i < packageCount; i++) {
21980                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21981                codePaths.add(ps.codePath.getAbsolutePath());
21982            }
21983            return codePaths;
21984        }
21985    }
21986
21987    /**
21988     * Examine all apps present on given mounted volume, and destroy apps that
21989     * aren't expected, either due to uninstallation or reinstallation on
21990     * another volume.
21991     */
21992    private void reconcileApps(String volumeUuid) {
21993        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21994        List<File> filesToDelete = null;
21995
21996        final File[] files = FileUtils.listFilesOrEmpty(
21997                Environment.getDataAppDirectory(volumeUuid));
21998        for (File file : files) {
21999            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22000                    && !PackageInstallerService.isStageName(file.getName());
22001            if (!isPackage) {
22002                // Ignore entries which are not packages
22003                continue;
22004            }
22005
22006            String absolutePath = file.getAbsolutePath();
22007
22008            boolean pathValid = false;
22009            final int absoluteCodePathCount = absoluteCodePaths.size();
22010            for (int i = 0; i < absoluteCodePathCount; i++) {
22011                String absoluteCodePath = absoluteCodePaths.get(i);
22012                if (absolutePath.startsWith(absoluteCodePath)) {
22013                    pathValid = true;
22014                    break;
22015                }
22016            }
22017
22018            if (!pathValid) {
22019                if (filesToDelete == null) {
22020                    filesToDelete = new ArrayList<>();
22021                }
22022                filesToDelete.add(file);
22023            }
22024        }
22025
22026        if (filesToDelete != null) {
22027            final int fileToDeleteCount = filesToDelete.size();
22028            for (int i = 0; i < fileToDeleteCount; i++) {
22029                File fileToDelete = filesToDelete.get(i);
22030                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22031                synchronized (mInstallLock) {
22032                    removeCodePathLI(fileToDelete);
22033                }
22034            }
22035        }
22036    }
22037
22038    /**
22039     * Reconcile all app data for the given user.
22040     * <p>
22041     * Verifies that directories exist and that ownership and labeling is
22042     * correct for all installed apps on all mounted volumes.
22043     */
22044    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22045        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22046        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22047            final String volumeUuid = vol.getFsUuid();
22048            synchronized (mInstallLock) {
22049                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22050            }
22051        }
22052    }
22053
22054    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22055            boolean migrateAppData) {
22056        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22057    }
22058
22059    /**
22060     * Reconcile all app data on given mounted volume.
22061     * <p>
22062     * Destroys app data that isn't expected, either due to uninstallation or
22063     * reinstallation on another volume.
22064     * <p>
22065     * Verifies that directories exist and that ownership and labeling is
22066     * correct for all installed apps.
22067     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22068     */
22069    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22070            boolean migrateAppData, boolean onlyCoreApps) {
22071        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22072                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22073        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22074
22075        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22076        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22077
22078        // First look for stale data that doesn't belong, and check if things
22079        // have changed since we did our last restorecon
22080        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22081            if (StorageManager.isFileEncryptedNativeOrEmulated()
22082                    && !StorageManager.isUserKeyUnlocked(userId)) {
22083                throw new RuntimeException(
22084                        "Yikes, someone asked us to reconcile CE storage while " + userId
22085                                + " was still locked; this would have caused massive data loss!");
22086            }
22087
22088            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22089            for (File file : files) {
22090                final String packageName = file.getName();
22091                try {
22092                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22093                } catch (PackageManagerException e) {
22094                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22095                    try {
22096                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22097                                StorageManager.FLAG_STORAGE_CE, 0);
22098                    } catch (InstallerException e2) {
22099                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22100                    }
22101                }
22102            }
22103        }
22104        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22105            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22106            for (File file : files) {
22107                final String packageName = file.getName();
22108                try {
22109                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22110                } catch (PackageManagerException e) {
22111                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22112                    try {
22113                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22114                                StorageManager.FLAG_STORAGE_DE, 0);
22115                    } catch (InstallerException e2) {
22116                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22117                    }
22118                }
22119            }
22120        }
22121
22122        // Ensure that data directories are ready to roll for all packages
22123        // installed for this volume and user
22124        final List<PackageSetting> packages;
22125        synchronized (mPackages) {
22126            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22127        }
22128        int preparedCount = 0;
22129        for (PackageSetting ps : packages) {
22130            final String packageName = ps.name;
22131            if (ps.pkg == null) {
22132                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22133                // TODO: might be due to legacy ASEC apps; we should circle back
22134                // and reconcile again once they're scanned
22135                continue;
22136            }
22137            // Skip non-core apps if requested
22138            if (onlyCoreApps && !ps.pkg.coreApp) {
22139                result.add(packageName);
22140                continue;
22141            }
22142
22143            if (ps.getInstalled(userId)) {
22144                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22145                preparedCount++;
22146            }
22147        }
22148
22149        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22150        return result;
22151    }
22152
22153    /**
22154     * Prepare app data for the given app just after it was installed or
22155     * upgraded. This method carefully only touches users that it's installed
22156     * for, and it forces a restorecon to handle any seinfo changes.
22157     * <p>
22158     * Verifies that directories exist and that ownership and labeling is
22159     * correct for all installed apps. If there is an ownership mismatch, it
22160     * will try recovering system apps by wiping data; third-party app data is
22161     * left intact.
22162     * <p>
22163     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22164     */
22165    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22166        final PackageSetting ps;
22167        synchronized (mPackages) {
22168            ps = mSettings.mPackages.get(pkg.packageName);
22169            mSettings.writeKernelMappingLPr(ps);
22170        }
22171
22172        final UserManager um = mContext.getSystemService(UserManager.class);
22173        UserManagerInternal umInternal = getUserManagerInternal();
22174        for (UserInfo user : um.getUsers()) {
22175            final int flags;
22176            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22177                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22178            } else if (umInternal.isUserRunning(user.id)) {
22179                flags = StorageManager.FLAG_STORAGE_DE;
22180            } else {
22181                continue;
22182            }
22183
22184            if (ps.getInstalled(user.id)) {
22185                // TODO: when user data is locked, mark that we're still dirty
22186                prepareAppDataLIF(pkg, user.id, flags);
22187            }
22188        }
22189    }
22190
22191    /**
22192     * Prepare app data for the given app.
22193     * <p>
22194     * Verifies that directories exist and that ownership and labeling is
22195     * correct for all installed apps. If there is an ownership mismatch, this
22196     * will try recovering system apps by wiping data; third-party app data is
22197     * left intact.
22198     */
22199    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22200        if (pkg == null) {
22201            Slog.wtf(TAG, "Package was null!", new Throwable());
22202            return;
22203        }
22204        prepareAppDataLeafLIF(pkg, userId, flags);
22205        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22206        for (int i = 0; i < childCount; i++) {
22207            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22208        }
22209    }
22210
22211    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22212            boolean maybeMigrateAppData) {
22213        prepareAppDataLIF(pkg, userId, flags);
22214
22215        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22216            // We may have just shuffled around app data directories, so
22217            // prepare them one more time
22218            prepareAppDataLIF(pkg, userId, flags);
22219        }
22220    }
22221
22222    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22223        if (DEBUG_APP_DATA) {
22224            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22225                    + Integer.toHexString(flags));
22226        }
22227
22228        final String volumeUuid = pkg.volumeUuid;
22229        final String packageName = pkg.packageName;
22230        final ApplicationInfo app = pkg.applicationInfo;
22231        final int appId = UserHandle.getAppId(app.uid);
22232
22233        Preconditions.checkNotNull(app.seInfo);
22234
22235        long ceDataInode = -1;
22236        try {
22237            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22238                    appId, app.seInfo, app.targetSdkVersion);
22239        } catch (InstallerException e) {
22240            if (app.isSystemApp()) {
22241                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22242                        + ", but trying to recover: " + e);
22243                destroyAppDataLeafLIF(pkg, userId, flags);
22244                try {
22245                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22246                            appId, app.seInfo, app.targetSdkVersion);
22247                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22248                } catch (InstallerException e2) {
22249                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22250                }
22251            } else {
22252                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22253            }
22254        }
22255        // Prepare the application profiles only for upgrades and first boot (so that we don't
22256        // repeat the same operation at each boot).
22257        // We only have to cover the upgrade and first boot here because for app installs we
22258        // prepare the profiles before invoking dexopt (in installPackageLI).
22259        //
22260        // We also have to cover non system users because we do not call the usual install package
22261        // methods for them.
22262        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22263            mArtManagerService.prepareAppProfiles(pkg, userId);
22264        }
22265
22266        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22267            // TODO: mark this structure as dirty so we persist it!
22268            synchronized (mPackages) {
22269                final PackageSetting ps = mSettings.mPackages.get(packageName);
22270                if (ps != null) {
22271                    ps.setCeDataInode(ceDataInode, userId);
22272                }
22273            }
22274        }
22275
22276        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22277    }
22278
22279    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22280        if (pkg == null) {
22281            Slog.wtf(TAG, "Package was null!", new Throwable());
22282            return;
22283        }
22284        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22285        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22286        for (int i = 0; i < childCount; i++) {
22287            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22288        }
22289    }
22290
22291    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22292        final String volumeUuid = pkg.volumeUuid;
22293        final String packageName = pkg.packageName;
22294        final ApplicationInfo app = pkg.applicationInfo;
22295
22296        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22297            // Create a native library symlink only if we have native libraries
22298            // and if the native libraries are 32 bit libraries. We do not provide
22299            // this symlink for 64 bit libraries.
22300            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22301                final String nativeLibPath = app.nativeLibraryDir;
22302                try {
22303                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22304                            nativeLibPath, userId);
22305                } catch (InstallerException e) {
22306                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22307                }
22308            }
22309        }
22310    }
22311
22312    /**
22313     * For system apps on non-FBE devices, this method migrates any existing
22314     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22315     * requested by the app.
22316     */
22317    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22318        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22319                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22320            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22321                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22322            try {
22323                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22324                        storageTarget);
22325            } catch (InstallerException e) {
22326                logCriticalInfo(Log.WARN,
22327                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22328            }
22329            return true;
22330        } else {
22331            return false;
22332        }
22333    }
22334
22335    public PackageFreezer freezePackage(String packageName, String killReason) {
22336        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22337    }
22338
22339    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22340        return new PackageFreezer(packageName, userId, killReason);
22341    }
22342
22343    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22344            String killReason) {
22345        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22346    }
22347
22348    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22349            String killReason) {
22350        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22351            return new PackageFreezer();
22352        } else {
22353            return freezePackage(packageName, userId, killReason);
22354        }
22355    }
22356
22357    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22358            String killReason) {
22359        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22360    }
22361
22362    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22363            String killReason) {
22364        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22365            return new PackageFreezer();
22366        } else {
22367            return freezePackage(packageName, userId, killReason);
22368        }
22369    }
22370
22371    /**
22372     * Class that freezes and kills the given package upon creation, and
22373     * unfreezes it upon closing. This is typically used when doing surgery on
22374     * app code/data to prevent the app from running while you're working.
22375     */
22376    private class PackageFreezer implements AutoCloseable {
22377        private final String mPackageName;
22378        private final PackageFreezer[] mChildren;
22379
22380        private final boolean mWeFroze;
22381
22382        private final AtomicBoolean mClosed = new AtomicBoolean();
22383        private final CloseGuard mCloseGuard = CloseGuard.get();
22384
22385        /**
22386         * Create and return a stub freezer that doesn't actually do anything,
22387         * typically used when someone requested
22388         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22389         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22390         */
22391        public PackageFreezer() {
22392            mPackageName = null;
22393            mChildren = null;
22394            mWeFroze = false;
22395            mCloseGuard.open("close");
22396        }
22397
22398        public PackageFreezer(String packageName, int userId, String killReason) {
22399            synchronized (mPackages) {
22400                mPackageName = packageName;
22401                mWeFroze = mFrozenPackages.add(mPackageName);
22402
22403                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22404                if (ps != null) {
22405                    killApplication(ps.name, ps.appId, userId, killReason);
22406                }
22407
22408                final PackageParser.Package p = mPackages.get(packageName);
22409                if (p != null && p.childPackages != null) {
22410                    final int N = p.childPackages.size();
22411                    mChildren = new PackageFreezer[N];
22412                    for (int i = 0; i < N; i++) {
22413                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22414                                userId, killReason);
22415                    }
22416                } else {
22417                    mChildren = null;
22418                }
22419            }
22420            mCloseGuard.open("close");
22421        }
22422
22423        @Override
22424        protected void finalize() throws Throwable {
22425            try {
22426                if (mCloseGuard != null) {
22427                    mCloseGuard.warnIfOpen();
22428                }
22429
22430                close();
22431            } finally {
22432                super.finalize();
22433            }
22434        }
22435
22436        @Override
22437        public void close() {
22438            mCloseGuard.close();
22439            if (mClosed.compareAndSet(false, true)) {
22440                synchronized (mPackages) {
22441                    if (mWeFroze) {
22442                        mFrozenPackages.remove(mPackageName);
22443                    }
22444
22445                    if (mChildren != null) {
22446                        for (PackageFreezer freezer : mChildren) {
22447                            freezer.close();
22448                        }
22449                    }
22450                }
22451            }
22452        }
22453    }
22454
22455    /**
22456     * Verify that given package is currently frozen.
22457     */
22458    private void checkPackageFrozen(String packageName) {
22459        synchronized (mPackages) {
22460            if (!mFrozenPackages.contains(packageName)) {
22461                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22462            }
22463        }
22464    }
22465
22466    @Override
22467    public int movePackage(final String packageName, final String volumeUuid) {
22468        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22469
22470        final int callingUid = Binder.getCallingUid();
22471        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22472        final int moveId = mNextMoveId.getAndIncrement();
22473        mHandler.post(new Runnable() {
22474            @Override
22475            public void run() {
22476                try {
22477                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22478                } catch (PackageManagerException e) {
22479                    Slog.w(TAG, "Failed to move " + packageName, e);
22480                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22481                }
22482            }
22483        });
22484        return moveId;
22485    }
22486
22487    private void movePackageInternal(final String packageName, final String volumeUuid,
22488            final int moveId, final int callingUid, UserHandle user)
22489                    throws PackageManagerException {
22490        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22491        final PackageManager pm = mContext.getPackageManager();
22492
22493        final boolean currentAsec;
22494        final String currentVolumeUuid;
22495        final File codeFile;
22496        final String installerPackageName;
22497        final String packageAbiOverride;
22498        final int appId;
22499        final String seinfo;
22500        final String label;
22501        final int targetSdkVersion;
22502        final PackageFreezer freezer;
22503        final int[] installedUserIds;
22504
22505        // reader
22506        synchronized (mPackages) {
22507            final PackageParser.Package pkg = mPackages.get(packageName);
22508            final PackageSetting ps = mSettings.mPackages.get(packageName);
22509            if (pkg == null
22510                    || ps == null
22511                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22512                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22513            }
22514            if (pkg.applicationInfo.isSystemApp()) {
22515                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22516                        "Cannot move system application");
22517            }
22518
22519            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22520            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22521                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22522            if (isInternalStorage && !allow3rdPartyOnInternal) {
22523                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22524                        "3rd party apps are not allowed on internal storage");
22525            }
22526
22527            if (pkg.applicationInfo.isExternalAsec()) {
22528                currentAsec = true;
22529                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22530            } else if (pkg.applicationInfo.isForwardLocked()) {
22531                currentAsec = true;
22532                currentVolumeUuid = "forward_locked";
22533            } else {
22534                currentAsec = false;
22535                currentVolumeUuid = ps.volumeUuid;
22536
22537                final File probe = new File(pkg.codePath);
22538                final File probeOat = new File(probe, "oat");
22539                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22540                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22541                            "Move only supported for modern cluster style installs");
22542                }
22543            }
22544
22545            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22546                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22547                        "Package already moved to " + volumeUuid);
22548            }
22549            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22550                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22551                        "Device admin cannot be moved");
22552            }
22553
22554            if (mFrozenPackages.contains(packageName)) {
22555                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22556                        "Failed to move already frozen package");
22557            }
22558
22559            codeFile = new File(pkg.codePath);
22560            installerPackageName = ps.installerPackageName;
22561            packageAbiOverride = ps.cpuAbiOverrideString;
22562            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22563            seinfo = pkg.applicationInfo.seInfo;
22564            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22565            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22566            freezer = freezePackage(packageName, "movePackageInternal");
22567            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22568        }
22569
22570        final Bundle extras = new Bundle();
22571        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22572        extras.putString(Intent.EXTRA_TITLE, label);
22573        mMoveCallbacks.notifyCreated(moveId, extras);
22574
22575        int installFlags;
22576        final boolean moveCompleteApp;
22577        final File measurePath;
22578
22579        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22580            installFlags = INSTALL_INTERNAL;
22581            moveCompleteApp = !currentAsec;
22582            measurePath = Environment.getDataAppDirectory(volumeUuid);
22583        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22584            installFlags = INSTALL_EXTERNAL;
22585            moveCompleteApp = false;
22586            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22587        } else {
22588            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22589            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22590                    || !volume.isMountedWritable()) {
22591                freezer.close();
22592                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22593                        "Move location not mounted private volume");
22594            }
22595
22596            Preconditions.checkState(!currentAsec);
22597
22598            installFlags = INSTALL_INTERNAL;
22599            moveCompleteApp = true;
22600            measurePath = Environment.getDataAppDirectory(volumeUuid);
22601        }
22602
22603        // If we're moving app data around, we need all the users unlocked
22604        if (moveCompleteApp) {
22605            for (int userId : installedUserIds) {
22606                if (StorageManager.isFileEncryptedNativeOrEmulated()
22607                        && !StorageManager.isUserKeyUnlocked(userId)) {
22608                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22609                            "User " + userId + " must be unlocked");
22610                }
22611            }
22612        }
22613
22614        final PackageStats stats = new PackageStats(null, -1);
22615        synchronized (mInstaller) {
22616            for (int userId : installedUserIds) {
22617                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22618                    freezer.close();
22619                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22620                            "Failed to measure package size");
22621                }
22622            }
22623        }
22624
22625        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22626                + stats.dataSize);
22627
22628        final long startFreeBytes = measurePath.getUsableSpace();
22629        final long sizeBytes;
22630        if (moveCompleteApp) {
22631            sizeBytes = stats.codeSize + stats.dataSize;
22632        } else {
22633            sizeBytes = stats.codeSize;
22634        }
22635
22636        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22637            freezer.close();
22638            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22639                    "Not enough free space to move");
22640        }
22641
22642        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22643
22644        final CountDownLatch installedLatch = new CountDownLatch(1);
22645        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22646            @Override
22647            public void onUserActionRequired(Intent intent) throws RemoteException {
22648                throw new IllegalStateException();
22649            }
22650
22651            @Override
22652            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22653                    Bundle extras) throws RemoteException {
22654                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22655                        + PackageManager.installStatusToString(returnCode, msg));
22656
22657                installedLatch.countDown();
22658                freezer.close();
22659
22660                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22661                switch (status) {
22662                    case PackageInstaller.STATUS_SUCCESS:
22663                        mMoveCallbacks.notifyStatusChanged(moveId,
22664                                PackageManager.MOVE_SUCCEEDED);
22665                        break;
22666                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22667                        mMoveCallbacks.notifyStatusChanged(moveId,
22668                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22669                        break;
22670                    default:
22671                        mMoveCallbacks.notifyStatusChanged(moveId,
22672                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22673                        break;
22674                }
22675            }
22676        };
22677
22678        final MoveInfo move;
22679        if (moveCompleteApp) {
22680            // Kick off a thread to report progress estimates
22681            new Thread() {
22682                @Override
22683                public void run() {
22684                    while (true) {
22685                        try {
22686                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22687                                break;
22688                            }
22689                        } catch (InterruptedException ignored) {
22690                        }
22691
22692                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22693                        final int progress = 10 + (int) MathUtils.constrain(
22694                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22695                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22696                    }
22697                }
22698            }.start();
22699
22700            final String dataAppName = codeFile.getName();
22701            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22702                    dataAppName, appId, seinfo, targetSdkVersion);
22703        } else {
22704            move = null;
22705        }
22706
22707        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22708
22709        final Message msg = mHandler.obtainMessage(INIT_COPY);
22710        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22711        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22712                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22713                packageAbiOverride, null /*grantedPermissions*/,
22714                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22715        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22716        msg.obj = params;
22717
22718        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22719                System.identityHashCode(msg.obj));
22720        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22721                System.identityHashCode(msg.obj));
22722
22723        mHandler.sendMessage(msg);
22724    }
22725
22726    @Override
22727    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22728        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22729
22730        final int realMoveId = mNextMoveId.getAndIncrement();
22731        final Bundle extras = new Bundle();
22732        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22733        mMoveCallbacks.notifyCreated(realMoveId, extras);
22734
22735        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22736            @Override
22737            public void onCreated(int moveId, Bundle extras) {
22738                // Ignored
22739            }
22740
22741            @Override
22742            public void onStatusChanged(int moveId, int status, long estMillis) {
22743                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22744            }
22745        };
22746
22747        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22748        storage.setPrimaryStorageUuid(volumeUuid, callback);
22749        return realMoveId;
22750    }
22751
22752    @Override
22753    public int getMoveStatus(int moveId) {
22754        mContext.enforceCallingOrSelfPermission(
22755                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22756        return mMoveCallbacks.mLastStatus.get(moveId);
22757    }
22758
22759    @Override
22760    public void registerMoveCallback(IPackageMoveObserver callback) {
22761        mContext.enforceCallingOrSelfPermission(
22762                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22763        mMoveCallbacks.register(callback);
22764    }
22765
22766    @Override
22767    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22768        mContext.enforceCallingOrSelfPermission(
22769                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22770        mMoveCallbacks.unregister(callback);
22771    }
22772
22773    @Override
22774    public boolean setInstallLocation(int loc) {
22775        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22776                null);
22777        if (getInstallLocation() == loc) {
22778            return true;
22779        }
22780        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22781                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22782            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22783                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22784            return true;
22785        }
22786        return false;
22787   }
22788
22789    @Override
22790    public int getInstallLocation() {
22791        // allow instant app access
22792        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22793                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22794                PackageHelper.APP_INSTALL_AUTO);
22795    }
22796
22797    /** Called by UserManagerService */
22798    void cleanUpUser(UserManagerService userManager, int userHandle) {
22799        synchronized (mPackages) {
22800            mDirtyUsers.remove(userHandle);
22801            mUserNeedsBadging.delete(userHandle);
22802            mSettings.removeUserLPw(userHandle);
22803            mPendingBroadcasts.remove(userHandle);
22804            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22805            removeUnusedPackagesLPw(userManager, userHandle);
22806        }
22807    }
22808
22809    /**
22810     * We're removing userHandle and would like to remove any downloaded packages
22811     * that are no longer in use by any other user.
22812     * @param userHandle the user being removed
22813     */
22814    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22815        final boolean DEBUG_CLEAN_APKS = false;
22816        int [] users = userManager.getUserIds();
22817        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22818        while (psit.hasNext()) {
22819            PackageSetting ps = psit.next();
22820            if (ps.pkg == null) {
22821                continue;
22822            }
22823            final String packageName = ps.pkg.packageName;
22824            // Skip over if system app
22825            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22826                continue;
22827            }
22828            if (DEBUG_CLEAN_APKS) {
22829                Slog.i(TAG, "Checking package " + packageName);
22830            }
22831            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22832            if (keep) {
22833                if (DEBUG_CLEAN_APKS) {
22834                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22835                }
22836            } else {
22837                for (int i = 0; i < users.length; i++) {
22838                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22839                        keep = true;
22840                        if (DEBUG_CLEAN_APKS) {
22841                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22842                                    + users[i]);
22843                        }
22844                        break;
22845                    }
22846                }
22847            }
22848            if (!keep) {
22849                if (DEBUG_CLEAN_APKS) {
22850                    Slog.i(TAG, "  Removing package " + packageName);
22851                }
22852                mHandler.post(new Runnable() {
22853                    public void run() {
22854                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22855                                userHandle, 0);
22856                    } //end run
22857                });
22858            }
22859        }
22860    }
22861
22862    /** Called by UserManagerService */
22863    void createNewUser(int userId, String[] disallowedPackages) {
22864        synchronized (mInstallLock) {
22865            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22866        }
22867        synchronized (mPackages) {
22868            scheduleWritePackageRestrictionsLocked(userId);
22869            scheduleWritePackageListLocked(userId);
22870            applyFactoryDefaultBrowserLPw(userId);
22871            primeDomainVerificationsLPw(userId);
22872        }
22873    }
22874
22875    void onNewUserCreated(final int userId) {
22876        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22877        synchronized(mPackages) {
22878            // If permission review for legacy apps is required, we represent
22879            // dagerous permissions for such apps as always granted runtime
22880            // permissions to keep per user flag state whether review is needed.
22881            // Hence, if a new user is added we have to propagate dangerous
22882            // permission grants for these legacy apps.
22883            if (mSettings.mPermissions.mPermissionReviewRequired) {
22884// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22885                mPermissionManager.updateAllPermissions(
22886                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22887                        mPermissionCallback);
22888            }
22889        }
22890    }
22891
22892    @Override
22893    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22894        mContext.enforceCallingOrSelfPermission(
22895                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22896                "Only package verification agents can read the verifier device identity");
22897
22898        synchronized (mPackages) {
22899            return mSettings.getVerifierDeviceIdentityLPw();
22900        }
22901    }
22902
22903    @Override
22904    public void setPermissionEnforced(String permission, boolean enforced) {
22905        // TODO: Now that we no longer change GID for storage, this should to away.
22906        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22907                "setPermissionEnforced");
22908        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22909            synchronized (mPackages) {
22910                if (mSettings.mReadExternalStorageEnforced == null
22911                        || mSettings.mReadExternalStorageEnforced != enforced) {
22912                    mSettings.mReadExternalStorageEnforced =
22913                            enforced ? Boolean.TRUE : Boolean.FALSE;
22914                    mSettings.writeLPr();
22915                }
22916            }
22917            // kill any non-foreground processes so we restart them and
22918            // grant/revoke the GID.
22919            final IActivityManager am = ActivityManager.getService();
22920            if (am != null) {
22921                final long token = Binder.clearCallingIdentity();
22922                try {
22923                    am.killProcessesBelowForeground("setPermissionEnforcement");
22924                } catch (RemoteException e) {
22925                } finally {
22926                    Binder.restoreCallingIdentity(token);
22927                }
22928            }
22929        } else {
22930            throw new IllegalArgumentException("No selective enforcement for " + permission);
22931        }
22932    }
22933
22934    @Override
22935    @Deprecated
22936    public boolean isPermissionEnforced(String permission) {
22937        // allow instant applications
22938        return true;
22939    }
22940
22941    @Override
22942    public boolean isStorageLow() {
22943        // allow instant applications
22944        final long token = Binder.clearCallingIdentity();
22945        try {
22946            final DeviceStorageMonitorInternal
22947                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22948            if (dsm != null) {
22949                return dsm.isMemoryLow();
22950            } else {
22951                return false;
22952            }
22953        } finally {
22954            Binder.restoreCallingIdentity(token);
22955        }
22956    }
22957
22958    @Override
22959    public IPackageInstaller getPackageInstaller() {
22960        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22961            return null;
22962        }
22963        return mInstallerService;
22964    }
22965
22966    @Override
22967    public IArtManager getArtManager() {
22968        return mArtManagerService;
22969    }
22970
22971    private boolean userNeedsBadging(int userId) {
22972        int index = mUserNeedsBadging.indexOfKey(userId);
22973        if (index < 0) {
22974            final UserInfo userInfo;
22975            final long token = Binder.clearCallingIdentity();
22976            try {
22977                userInfo = sUserManager.getUserInfo(userId);
22978            } finally {
22979                Binder.restoreCallingIdentity(token);
22980            }
22981            final boolean b;
22982            if (userInfo != null && userInfo.isManagedProfile()) {
22983                b = true;
22984            } else {
22985                b = false;
22986            }
22987            mUserNeedsBadging.put(userId, b);
22988            return b;
22989        }
22990        return mUserNeedsBadging.valueAt(index);
22991    }
22992
22993    @Override
22994    public KeySet getKeySetByAlias(String packageName, String alias) {
22995        if (packageName == null || alias == null) {
22996            return null;
22997        }
22998        synchronized(mPackages) {
22999            final PackageParser.Package pkg = mPackages.get(packageName);
23000            if (pkg == null) {
23001                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23002                throw new IllegalArgumentException("Unknown package: " + packageName);
23003            }
23004            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23005            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23006                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23007                throw new IllegalArgumentException("Unknown package: " + packageName);
23008            }
23009            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23010            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23011        }
23012    }
23013
23014    @Override
23015    public KeySet getSigningKeySet(String packageName) {
23016        if (packageName == null) {
23017            return null;
23018        }
23019        synchronized(mPackages) {
23020            final int callingUid = Binder.getCallingUid();
23021            final int callingUserId = UserHandle.getUserId(callingUid);
23022            final PackageParser.Package pkg = mPackages.get(packageName);
23023            if (pkg == null) {
23024                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23025                throw new IllegalArgumentException("Unknown package: " + packageName);
23026            }
23027            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23028            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23029                // filter and pretend the package doesn't exist
23030                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23031                        + ", uid:" + callingUid);
23032                throw new IllegalArgumentException("Unknown package: " + packageName);
23033            }
23034            if (pkg.applicationInfo.uid != callingUid
23035                    && Process.SYSTEM_UID != callingUid) {
23036                throw new SecurityException("May not access signing KeySet of other apps.");
23037            }
23038            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23039            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23040        }
23041    }
23042
23043    @Override
23044    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23045        final int callingUid = Binder.getCallingUid();
23046        if (getInstantAppPackageName(callingUid) != null) {
23047            return false;
23048        }
23049        if (packageName == null || ks == null) {
23050            return false;
23051        }
23052        synchronized(mPackages) {
23053            final PackageParser.Package pkg = mPackages.get(packageName);
23054            if (pkg == null
23055                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23056                            UserHandle.getUserId(callingUid))) {
23057                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23058                throw new IllegalArgumentException("Unknown package: " + packageName);
23059            }
23060            IBinder ksh = ks.getToken();
23061            if (ksh instanceof KeySetHandle) {
23062                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23063                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23064            }
23065            return false;
23066        }
23067    }
23068
23069    @Override
23070    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23071        final int callingUid = Binder.getCallingUid();
23072        if (getInstantAppPackageName(callingUid) != null) {
23073            return false;
23074        }
23075        if (packageName == null || ks == null) {
23076            return false;
23077        }
23078        synchronized(mPackages) {
23079            final PackageParser.Package pkg = mPackages.get(packageName);
23080            if (pkg == null
23081                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23082                            UserHandle.getUserId(callingUid))) {
23083                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23084                throw new IllegalArgumentException("Unknown package: " + packageName);
23085            }
23086            IBinder ksh = ks.getToken();
23087            if (ksh instanceof KeySetHandle) {
23088                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23089                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23090            }
23091            return false;
23092        }
23093    }
23094
23095    private void deletePackageIfUnusedLPr(final String packageName) {
23096        PackageSetting ps = mSettings.mPackages.get(packageName);
23097        if (ps == null) {
23098            return;
23099        }
23100        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23101            // TODO Implement atomic delete if package is unused
23102            // It is currently possible that the package will be deleted even if it is installed
23103            // after this method returns.
23104            mHandler.post(new Runnable() {
23105                public void run() {
23106                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23107                            0, PackageManager.DELETE_ALL_USERS);
23108                }
23109            });
23110        }
23111    }
23112
23113    /**
23114     * Check and throw if the given before/after packages would be considered a
23115     * downgrade.
23116     */
23117    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23118            throws PackageManagerException {
23119        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23120            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23121                    "Update version code " + after.versionCode + " is older than current "
23122                    + before.getLongVersionCode());
23123        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23124            if (after.baseRevisionCode < before.baseRevisionCode) {
23125                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23126                        "Update base revision code " + after.baseRevisionCode
23127                        + " is older than current " + before.baseRevisionCode);
23128            }
23129
23130            if (!ArrayUtils.isEmpty(after.splitNames)) {
23131                for (int i = 0; i < after.splitNames.length; i++) {
23132                    final String splitName = after.splitNames[i];
23133                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23134                    if (j != -1) {
23135                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23136                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23137                                    "Update split " + splitName + " revision code "
23138                                    + after.splitRevisionCodes[i] + " is older than current "
23139                                    + before.splitRevisionCodes[j]);
23140                        }
23141                    }
23142                }
23143            }
23144        }
23145    }
23146
23147    private static class MoveCallbacks extends Handler {
23148        private static final int MSG_CREATED = 1;
23149        private static final int MSG_STATUS_CHANGED = 2;
23150
23151        private final RemoteCallbackList<IPackageMoveObserver>
23152                mCallbacks = new RemoteCallbackList<>();
23153
23154        private final SparseIntArray mLastStatus = new SparseIntArray();
23155
23156        public MoveCallbacks(Looper looper) {
23157            super(looper);
23158        }
23159
23160        public void register(IPackageMoveObserver callback) {
23161            mCallbacks.register(callback);
23162        }
23163
23164        public void unregister(IPackageMoveObserver callback) {
23165            mCallbacks.unregister(callback);
23166        }
23167
23168        @Override
23169        public void handleMessage(Message msg) {
23170            final SomeArgs args = (SomeArgs) msg.obj;
23171            final int n = mCallbacks.beginBroadcast();
23172            for (int i = 0; i < n; i++) {
23173                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23174                try {
23175                    invokeCallback(callback, msg.what, args);
23176                } catch (RemoteException ignored) {
23177                }
23178            }
23179            mCallbacks.finishBroadcast();
23180            args.recycle();
23181        }
23182
23183        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23184                throws RemoteException {
23185            switch (what) {
23186                case MSG_CREATED: {
23187                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23188                    break;
23189                }
23190                case MSG_STATUS_CHANGED: {
23191                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23192                    break;
23193                }
23194            }
23195        }
23196
23197        private void notifyCreated(int moveId, Bundle extras) {
23198            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23199
23200            final SomeArgs args = SomeArgs.obtain();
23201            args.argi1 = moveId;
23202            args.arg2 = extras;
23203            obtainMessage(MSG_CREATED, args).sendToTarget();
23204        }
23205
23206        private void notifyStatusChanged(int moveId, int status) {
23207            notifyStatusChanged(moveId, status, -1);
23208        }
23209
23210        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23211            Slog.v(TAG, "Move " + moveId + " status " + status);
23212
23213            final SomeArgs args = SomeArgs.obtain();
23214            args.argi1 = moveId;
23215            args.argi2 = status;
23216            args.arg3 = estMillis;
23217            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23218
23219            synchronized (mLastStatus) {
23220                mLastStatus.put(moveId, status);
23221            }
23222        }
23223    }
23224
23225    private final static class OnPermissionChangeListeners extends Handler {
23226        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23227
23228        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23229                new RemoteCallbackList<>();
23230
23231        public OnPermissionChangeListeners(Looper looper) {
23232            super(looper);
23233        }
23234
23235        @Override
23236        public void handleMessage(Message msg) {
23237            switch (msg.what) {
23238                case MSG_ON_PERMISSIONS_CHANGED: {
23239                    final int uid = msg.arg1;
23240                    handleOnPermissionsChanged(uid);
23241                } break;
23242            }
23243        }
23244
23245        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23246            mPermissionListeners.register(listener);
23247
23248        }
23249
23250        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23251            mPermissionListeners.unregister(listener);
23252        }
23253
23254        public void onPermissionsChanged(int uid) {
23255            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23256                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23257            }
23258        }
23259
23260        private void handleOnPermissionsChanged(int uid) {
23261            final int count = mPermissionListeners.beginBroadcast();
23262            try {
23263                for (int i = 0; i < count; i++) {
23264                    IOnPermissionsChangeListener callback = mPermissionListeners
23265                            .getBroadcastItem(i);
23266                    try {
23267                        callback.onPermissionsChanged(uid);
23268                    } catch (RemoteException e) {
23269                        Log.e(TAG, "Permission listener is dead", e);
23270                    }
23271                }
23272            } finally {
23273                mPermissionListeners.finishBroadcast();
23274            }
23275        }
23276    }
23277
23278    private class PackageManagerNative extends IPackageManagerNative.Stub {
23279        @Override
23280        public String[] getNamesForUids(int[] uids) throws RemoteException {
23281            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23282            // massage results so they can be parsed by the native binder
23283            for (int i = results.length - 1; i >= 0; --i) {
23284                if (results[i] == null) {
23285                    results[i] = "";
23286                }
23287            }
23288            return results;
23289        }
23290
23291        // NB: this differentiates between preloads and sideloads
23292        @Override
23293        public String getInstallerForPackage(String packageName) throws RemoteException {
23294            final String installerName = getInstallerPackageName(packageName);
23295            if (!TextUtils.isEmpty(installerName)) {
23296                return installerName;
23297            }
23298            // differentiate between preload and sideload
23299            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23300            ApplicationInfo appInfo = getApplicationInfo(packageName,
23301                                    /*flags*/ 0,
23302                                    /*userId*/ callingUser);
23303            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23304                return "preload";
23305            }
23306            return "";
23307        }
23308
23309        @Override
23310        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23311            try {
23312                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23313                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23314                if (pInfo != null) {
23315                    return pInfo.getLongVersionCode();
23316                }
23317            } catch (Exception e) {
23318            }
23319            return 0;
23320        }
23321    }
23322
23323    private class PackageManagerInternalImpl extends PackageManagerInternal {
23324        @Override
23325        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23326                int flagValues, int userId) {
23327            PackageManagerService.this.updatePermissionFlags(
23328                    permName, packageName, flagMask, flagValues, userId);
23329        }
23330
23331        @Override
23332        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23333            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23334        }
23335
23336        @Override
23337        public boolean isInstantApp(String packageName, int userId) {
23338            return PackageManagerService.this.isInstantApp(packageName, userId);
23339        }
23340
23341        @Override
23342        public String getInstantAppPackageName(int uid) {
23343            return PackageManagerService.this.getInstantAppPackageName(uid);
23344        }
23345
23346        @Override
23347        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23348            synchronized (mPackages) {
23349                return PackageManagerService.this.filterAppAccessLPr(
23350                        (PackageSetting) pkg.mExtras, callingUid, userId);
23351            }
23352        }
23353
23354        @Override
23355        public PackageParser.Package getPackage(String packageName) {
23356            synchronized (mPackages) {
23357                packageName = resolveInternalPackageNameLPr(
23358                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23359                return mPackages.get(packageName);
23360            }
23361        }
23362
23363        @Override
23364        public PackageList getPackageList(PackageListObserver observer) {
23365            synchronized (mPackages) {
23366                final int N = mPackages.size();
23367                final ArrayList<String> list = new ArrayList<>(N);
23368                for (int i = 0; i < N; i++) {
23369                    list.add(mPackages.keyAt(i));
23370                }
23371                final PackageList packageList = new PackageList(list, observer);
23372                if (observer != null) {
23373                    mPackageListObservers.add(packageList);
23374                }
23375                return packageList;
23376            }
23377        }
23378
23379        @Override
23380        public void removePackageListObserver(PackageListObserver observer) {
23381            synchronized (mPackages) {
23382                mPackageListObservers.remove(observer);
23383            }
23384        }
23385
23386        @Override
23387        public PackageParser.Package getDisabledPackage(String packageName) {
23388            synchronized (mPackages) {
23389                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23390                return (ps != null) ? ps.pkg : null;
23391            }
23392        }
23393
23394        @Override
23395        public String getKnownPackageName(int knownPackage, int userId) {
23396            switch(knownPackage) {
23397                case PackageManagerInternal.PACKAGE_BROWSER:
23398                    return getDefaultBrowserPackageName(userId);
23399                case PackageManagerInternal.PACKAGE_INSTALLER:
23400                    return mRequiredInstallerPackage;
23401                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23402                    return mSetupWizardPackage;
23403                case PackageManagerInternal.PACKAGE_SYSTEM:
23404                    return "android";
23405                case PackageManagerInternal.PACKAGE_VERIFIER:
23406                    return mRequiredVerifierPackage;
23407            }
23408            return null;
23409        }
23410
23411        @Override
23412        public boolean isResolveActivityComponent(ComponentInfo component) {
23413            return mResolveActivity.packageName.equals(component.packageName)
23414                    && mResolveActivity.name.equals(component.name);
23415        }
23416
23417        @Override
23418        public void setLocationPackagesProvider(PackagesProvider provider) {
23419            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23420        }
23421
23422        @Override
23423        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23424            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23425        }
23426
23427        @Override
23428        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23429            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23430        }
23431
23432        @Override
23433        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23434            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23435        }
23436
23437        @Override
23438        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23439            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23440        }
23441
23442        @Override
23443        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23444            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23445        }
23446
23447        @Override
23448        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23449            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23450        }
23451
23452        @Override
23453        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23454            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23455        }
23456
23457        @Override
23458        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23459            synchronized (mPackages) {
23460                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23461            }
23462            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23463        }
23464
23465        @Override
23466        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23467            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23468                    packageName, userId);
23469        }
23470
23471        @Override
23472        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23473            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23474                    packageName, userId);
23475        }
23476
23477        @Override
23478        public void setKeepUninstalledPackages(final List<String> packageList) {
23479            Preconditions.checkNotNull(packageList);
23480            List<String> removedFromList = null;
23481            synchronized (mPackages) {
23482                if (mKeepUninstalledPackages != null) {
23483                    final int packagesCount = mKeepUninstalledPackages.size();
23484                    for (int i = 0; i < packagesCount; i++) {
23485                        String oldPackage = mKeepUninstalledPackages.get(i);
23486                        if (packageList != null && packageList.contains(oldPackage)) {
23487                            continue;
23488                        }
23489                        if (removedFromList == null) {
23490                            removedFromList = new ArrayList<>();
23491                        }
23492                        removedFromList.add(oldPackage);
23493                    }
23494                }
23495                mKeepUninstalledPackages = new ArrayList<>(packageList);
23496                if (removedFromList != null) {
23497                    final int removedCount = removedFromList.size();
23498                    for (int i = 0; i < removedCount; i++) {
23499                        deletePackageIfUnusedLPr(removedFromList.get(i));
23500                    }
23501                }
23502            }
23503        }
23504
23505        @Override
23506        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23507            synchronized (mPackages) {
23508                return mPermissionManager.isPermissionsReviewRequired(
23509                        mPackages.get(packageName), userId);
23510            }
23511        }
23512
23513        @Override
23514        public PackageInfo getPackageInfo(
23515                String packageName, int flags, int filterCallingUid, int userId) {
23516            return PackageManagerService.this
23517                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23518                            flags, filterCallingUid, userId);
23519        }
23520
23521        @Override
23522        public int getPackageUid(String packageName, int flags, int userId) {
23523            return PackageManagerService.this
23524                    .getPackageUid(packageName, flags, userId);
23525        }
23526
23527        @Override
23528        public ApplicationInfo getApplicationInfo(
23529                String packageName, int flags, int filterCallingUid, int userId) {
23530            return PackageManagerService.this
23531                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23532        }
23533
23534        @Override
23535        public ActivityInfo getActivityInfo(
23536                ComponentName component, int flags, int filterCallingUid, int userId) {
23537            return PackageManagerService.this
23538                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23539        }
23540
23541        @Override
23542        public List<ResolveInfo> queryIntentActivities(
23543                Intent intent, int flags, int filterCallingUid, int userId) {
23544            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23545            return PackageManagerService.this
23546                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23547                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23548        }
23549
23550        @Override
23551        public List<ResolveInfo> queryIntentServices(
23552                Intent intent, int flags, int callingUid, int userId) {
23553            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23554            return PackageManagerService.this
23555                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23556                            false);
23557        }
23558
23559        @Override
23560        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23561                int userId) {
23562            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23563        }
23564
23565        @Override
23566        public void setDeviceAndProfileOwnerPackages(
23567                int deviceOwnerUserId, String deviceOwnerPackage,
23568                SparseArray<String> profileOwnerPackages) {
23569            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23570                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23571        }
23572
23573        @Override
23574        public boolean isPackageDataProtected(int userId, String packageName) {
23575            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23576        }
23577
23578        @Override
23579        public boolean isPackageEphemeral(int userId, String packageName) {
23580            synchronized (mPackages) {
23581                final PackageSetting ps = mSettings.mPackages.get(packageName);
23582                return ps != null ? ps.getInstantApp(userId) : false;
23583            }
23584        }
23585
23586        @Override
23587        public boolean wasPackageEverLaunched(String packageName, int userId) {
23588            synchronized (mPackages) {
23589                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23590            }
23591        }
23592
23593        @Override
23594        public void grantRuntimePermission(String packageName, String permName, int userId,
23595                boolean overridePolicy) {
23596            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23597                    permName, packageName, overridePolicy, getCallingUid(), userId,
23598                    mPermissionCallback);
23599        }
23600
23601        @Override
23602        public void revokeRuntimePermission(String packageName, String permName, int userId,
23603                boolean overridePolicy) {
23604            mPermissionManager.revokeRuntimePermission(
23605                    permName, packageName, overridePolicy, getCallingUid(), userId,
23606                    mPermissionCallback);
23607        }
23608
23609        @Override
23610        public String getNameForUid(int uid) {
23611            return PackageManagerService.this.getNameForUid(uid);
23612        }
23613
23614        @Override
23615        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23616                Intent origIntent, String resolvedType, String callingPackage,
23617                Bundle verificationBundle, int userId) {
23618            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23619                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23620                    userId);
23621        }
23622
23623        @Override
23624        public void grantEphemeralAccess(int userId, Intent intent,
23625                int targetAppId, int ephemeralAppId) {
23626            synchronized (mPackages) {
23627                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23628                        targetAppId, ephemeralAppId);
23629            }
23630        }
23631
23632        @Override
23633        public boolean isInstantAppInstallerComponent(ComponentName component) {
23634            synchronized (mPackages) {
23635                return mInstantAppInstallerActivity != null
23636                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23637            }
23638        }
23639
23640        @Override
23641        public void pruneInstantApps() {
23642            mInstantAppRegistry.pruneInstantApps();
23643        }
23644
23645        @Override
23646        public String getSetupWizardPackageName() {
23647            return mSetupWizardPackage;
23648        }
23649
23650        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23651            if (policy != null) {
23652                mExternalSourcesPolicy = policy;
23653            }
23654        }
23655
23656        @Override
23657        public boolean isPackagePersistent(String packageName) {
23658            synchronized (mPackages) {
23659                PackageParser.Package pkg = mPackages.get(packageName);
23660                return pkg != null
23661                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23662                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23663                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23664                        : false;
23665            }
23666        }
23667
23668        @Override
23669        public boolean isLegacySystemApp(Package pkg) {
23670            synchronized (mPackages) {
23671                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23672                return mPromoteSystemApps
23673                        && ps.isSystem()
23674                        && mExistingSystemPackages.contains(ps.name);
23675            }
23676        }
23677
23678        @Override
23679        public List<PackageInfo> getOverlayPackages(int userId) {
23680            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23681            synchronized (mPackages) {
23682                for (PackageParser.Package p : mPackages.values()) {
23683                    if (p.mOverlayTarget != null) {
23684                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23685                        if (pkg != null) {
23686                            overlayPackages.add(pkg);
23687                        }
23688                    }
23689                }
23690            }
23691            return overlayPackages;
23692        }
23693
23694        @Override
23695        public List<String> getTargetPackageNames(int userId) {
23696            List<String> targetPackages = new ArrayList<>();
23697            synchronized (mPackages) {
23698                for (PackageParser.Package p : mPackages.values()) {
23699                    if (p.mOverlayTarget == null) {
23700                        targetPackages.add(p.packageName);
23701                    }
23702                }
23703            }
23704            return targetPackages;
23705        }
23706
23707        @Override
23708        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23709                @Nullable List<String> overlayPackageNames) {
23710            synchronized (mPackages) {
23711                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23712                    Slog.e(TAG, "failed to find package " + targetPackageName);
23713                    return false;
23714                }
23715                ArrayList<String> overlayPaths = null;
23716                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23717                    final int N = overlayPackageNames.size();
23718                    overlayPaths = new ArrayList<>(N);
23719                    for (int i = 0; i < N; i++) {
23720                        final String packageName = overlayPackageNames.get(i);
23721                        final PackageParser.Package pkg = mPackages.get(packageName);
23722                        if (pkg == null) {
23723                            Slog.e(TAG, "failed to find package " + packageName);
23724                            return false;
23725                        }
23726                        overlayPaths.add(pkg.baseCodePath);
23727                    }
23728                }
23729
23730                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23731                ps.setOverlayPaths(overlayPaths, userId);
23732                return true;
23733            }
23734        }
23735
23736        @Override
23737        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23738                int flags, int userId, boolean resolveForStart) {
23739            return resolveIntentInternal(
23740                    intent, resolvedType, flags, userId, resolveForStart);
23741        }
23742
23743        @Override
23744        public ResolveInfo resolveService(Intent intent, String resolvedType,
23745                int flags, int userId, int callingUid) {
23746            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23747        }
23748
23749        @Override
23750        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23751            return PackageManagerService.this.resolveContentProviderInternal(
23752                    name, flags, userId);
23753        }
23754
23755        @Override
23756        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23757            synchronized (mPackages) {
23758                mIsolatedOwners.put(isolatedUid, ownerUid);
23759            }
23760        }
23761
23762        @Override
23763        public void removeIsolatedUid(int isolatedUid) {
23764            synchronized (mPackages) {
23765                mIsolatedOwners.delete(isolatedUid);
23766            }
23767        }
23768
23769        @Override
23770        public int getUidTargetSdkVersion(int uid) {
23771            synchronized (mPackages) {
23772                return getUidTargetSdkVersionLockedLPr(uid);
23773            }
23774        }
23775
23776        @Override
23777        public int getPackageTargetSdkVersion(String packageName) {
23778            synchronized (mPackages) {
23779                return getPackageTargetSdkVersionLockedLPr(packageName);
23780            }
23781        }
23782
23783        @Override
23784        public boolean canAccessInstantApps(int callingUid, int userId) {
23785            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23786        }
23787
23788        @Override
23789        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23790            synchronized (mPackages) {
23791                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23792            }
23793        }
23794
23795        @Override
23796        public void notifyPackageUse(String packageName, int reason) {
23797            synchronized (mPackages) {
23798                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23799            }
23800        }
23801    }
23802
23803    @Override
23804    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23805        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23806        synchronized (mPackages) {
23807            final long identity = Binder.clearCallingIdentity();
23808            try {
23809                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23810                        packageNames, userId);
23811            } finally {
23812                Binder.restoreCallingIdentity(identity);
23813            }
23814        }
23815    }
23816
23817    @Override
23818    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23819        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23820        synchronized (mPackages) {
23821            final long identity = Binder.clearCallingIdentity();
23822            try {
23823                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23824                        packageNames, userId);
23825            } finally {
23826                Binder.restoreCallingIdentity(identity);
23827            }
23828        }
23829    }
23830
23831    private static void enforceSystemOrPhoneCaller(String tag) {
23832        int callingUid = Binder.getCallingUid();
23833        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23834            throw new SecurityException(
23835                    "Cannot call " + tag + " from UID " + callingUid);
23836        }
23837    }
23838
23839    boolean isHistoricalPackageUsageAvailable() {
23840        return mPackageUsage.isHistoricalPackageUsageAvailable();
23841    }
23842
23843    /**
23844     * Return a <b>copy</b> of the collection of packages known to the package manager.
23845     * @return A copy of the values of mPackages.
23846     */
23847    Collection<PackageParser.Package> getPackages() {
23848        synchronized (mPackages) {
23849            return new ArrayList<>(mPackages.values());
23850        }
23851    }
23852
23853    /**
23854     * Logs process start information (including base APK hash) to the security log.
23855     * @hide
23856     */
23857    @Override
23858    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23859            String apkFile, int pid) {
23860        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23861            return;
23862        }
23863        if (!SecurityLog.isLoggingEnabled()) {
23864            return;
23865        }
23866        Bundle data = new Bundle();
23867        data.putLong("startTimestamp", System.currentTimeMillis());
23868        data.putString("processName", processName);
23869        data.putInt("uid", uid);
23870        data.putString("seinfo", seinfo);
23871        data.putString("apkFile", apkFile);
23872        data.putInt("pid", pid);
23873        Message msg = mProcessLoggingHandler.obtainMessage(
23874                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23875        msg.setData(data);
23876        mProcessLoggingHandler.sendMessage(msg);
23877    }
23878
23879    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23880        return mCompilerStats.getPackageStats(pkgName);
23881    }
23882
23883    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23884        return getOrCreateCompilerPackageStats(pkg.packageName);
23885    }
23886
23887    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23888        return mCompilerStats.getOrCreatePackageStats(pkgName);
23889    }
23890
23891    public void deleteCompilerPackageStats(String pkgName) {
23892        mCompilerStats.deletePackageStats(pkgName);
23893    }
23894
23895    @Override
23896    public int getInstallReason(String packageName, int userId) {
23897        final int callingUid = Binder.getCallingUid();
23898        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23899                true /* requireFullPermission */, false /* checkShell */,
23900                "get install reason");
23901        synchronized (mPackages) {
23902            final PackageSetting ps = mSettings.mPackages.get(packageName);
23903            if (filterAppAccessLPr(ps, callingUid, userId)) {
23904                return PackageManager.INSTALL_REASON_UNKNOWN;
23905            }
23906            if (ps != null) {
23907                return ps.getInstallReason(userId);
23908            }
23909        }
23910        return PackageManager.INSTALL_REASON_UNKNOWN;
23911    }
23912
23913    @Override
23914    public boolean canRequestPackageInstalls(String packageName, int userId) {
23915        return canRequestPackageInstallsInternal(packageName, 0, userId,
23916                true /* throwIfPermNotDeclared*/);
23917    }
23918
23919    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23920            boolean throwIfPermNotDeclared) {
23921        int callingUid = Binder.getCallingUid();
23922        int uid = getPackageUid(packageName, 0, userId);
23923        if (callingUid != uid && callingUid != Process.ROOT_UID
23924                && callingUid != Process.SYSTEM_UID) {
23925            throw new SecurityException(
23926                    "Caller uid " + callingUid + " does not own package " + packageName);
23927        }
23928        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23929        if (info == null) {
23930            return false;
23931        }
23932        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23933            return false;
23934        }
23935        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23936        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23937        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23938            if (throwIfPermNotDeclared) {
23939                throw new SecurityException("Need to declare " + appOpPermission
23940                        + " to call this api");
23941            } else {
23942                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23943                return false;
23944            }
23945        }
23946        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23947            return false;
23948        }
23949        if (mExternalSourcesPolicy != null) {
23950            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23951            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23952                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23953            }
23954        }
23955        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23956    }
23957
23958    @Override
23959    public ComponentName getInstantAppResolverSettingsComponent() {
23960        return mInstantAppResolverSettingsComponent;
23961    }
23962
23963    @Override
23964    public ComponentName getInstantAppInstallerComponent() {
23965        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23966            return null;
23967        }
23968        return mInstantAppInstallerActivity == null
23969                ? null : mInstantAppInstallerActivity.getComponentName();
23970    }
23971
23972    @Override
23973    public String getInstantAppAndroidId(String packageName, int userId) {
23974        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23975                "getInstantAppAndroidId");
23976        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23977                true /* requireFullPermission */, false /* checkShell */,
23978                "getInstantAppAndroidId");
23979        // Make sure the target is an Instant App.
23980        if (!isInstantApp(packageName, userId)) {
23981            return null;
23982        }
23983        synchronized (mPackages) {
23984            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23985        }
23986    }
23987
23988    boolean canHaveOatDir(String packageName) {
23989        synchronized (mPackages) {
23990            PackageParser.Package p = mPackages.get(packageName);
23991            if (p == null) {
23992                return false;
23993            }
23994            return p.canHaveOatDir();
23995        }
23996    }
23997
23998    private String getOatDir(PackageParser.Package pkg) {
23999        if (!pkg.canHaveOatDir()) {
24000            return null;
24001        }
24002        File codePath = new File(pkg.codePath);
24003        if (codePath.isDirectory()) {
24004            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24005        }
24006        return null;
24007    }
24008
24009    void deleteOatArtifactsOfPackage(String packageName) {
24010        final String[] instructionSets;
24011        final List<String> codePaths;
24012        final String oatDir;
24013        final PackageParser.Package pkg;
24014        synchronized (mPackages) {
24015            pkg = mPackages.get(packageName);
24016        }
24017        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24018        codePaths = pkg.getAllCodePaths();
24019        oatDir = getOatDir(pkg);
24020
24021        for (String codePath : codePaths) {
24022            for (String isa : instructionSets) {
24023                try {
24024                    mInstaller.deleteOdex(codePath, isa, oatDir);
24025                } catch (InstallerException e) {
24026                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24027                }
24028            }
24029        }
24030    }
24031
24032    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24033        Set<String> unusedPackages = new HashSet<>();
24034        long currentTimeInMillis = System.currentTimeMillis();
24035        synchronized (mPackages) {
24036            for (PackageParser.Package pkg : mPackages.values()) {
24037                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24038                if (ps == null) {
24039                    continue;
24040                }
24041                PackageDexUsage.PackageUseInfo packageUseInfo =
24042                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24043                if (PackageManagerServiceUtils
24044                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24045                                downgradeTimeThresholdMillis, packageUseInfo,
24046                                pkg.getLatestPackageUseTimeInMills(),
24047                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24048                    unusedPackages.add(pkg.packageName);
24049                }
24050            }
24051        }
24052        return unusedPackages;
24053    }
24054
24055    @Override
24056    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24057            int userId) {
24058        final int callingUid = Binder.getCallingUid();
24059        final int callingAppId = UserHandle.getAppId(callingUid);
24060
24061        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24062                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24063
24064        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24065                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24066            throw new SecurityException("Caller must have the "
24067                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24068        }
24069
24070        synchronized(mPackages) {
24071            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24072            scheduleWritePackageRestrictionsLocked(userId);
24073        }
24074    }
24075
24076    @Nullable
24077    @Override
24078    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24079        final int callingUid = Binder.getCallingUid();
24080        final int callingAppId = UserHandle.getAppId(callingUid);
24081
24082        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24083                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24084
24085        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24086                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24087            throw new SecurityException("Caller must have the "
24088                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24089        }
24090
24091        synchronized(mPackages) {
24092            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24093        }
24094    }
24095}
24096
24097interface PackageSender {
24098    /**
24099     * @param userIds User IDs where the action occurred on a full application
24100     * @param instantUserIds User IDs where the action occurred on an instant application
24101     */
24102    void sendPackageBroadcast(final String action, final String pkg,
24103        final Bundle extras, final int flags, final String targetPkg,
24104        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24105    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24106        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24107    void notifyPackageAdded(String packageName);
24108    void notifyPackageRemoved(String packageName);
24109}
24110